Skip to main content

Python type code generator

Project description

CircleCI codecov

py2ts

Covert Python dataclass and Enum to TypeScript interface.

Mapping of Scalar Types

assert python_type_to_typescript(str) == "string"
assert python_type_to_typescript(int) == "number"
assert python_type_to_typescript(bool) == "boolean"
assert python_type_to_typescript(float) == "number"
assert python_type_to_typescript(datetime) == "string"
assert python_type_to_typescript(date) == "string"
assert python_type_to_typescript(Decimal) == "string"
assert python_type_to_typescript(dict) == "{}"
assert python_type_to_typescript(list) == "Array<any>"

Usage

Create a schema with Python dataclass:

class EnumFruit(Enum):
    APPLE = "APPLE"
    ORANGE = "ORANGE"


@dataclass
class NestedSchema:
    string_field: str
    nullable_datetime_field: Optional[datetime]
    recursively_nested_field: Optional["NestedSchema"]


@dataclass
class ComplexSchema:
    nullable_int_field: Optional[int]
    nullable_decimal_field: Optional[int]
    nullable_enum_field: Optional[EnumFruit]
    nullable_nested_field: Optional[NestedSchema]
    nested_list_field: List[NestedSchema]

blocks = []
for path, node in schemas2typescript([ComplexSchema]).items():
    blocks.append(node.to_typescript())

print("\n".join(blocks))

The output is:

export enum EnumFruit {
  APPLE = 'APPLE',
  ORANGE = 'ORANGE'
}
export interface NestedSchema {
  string_field: string;
  nullable_datetime_field: string | null;
  recursively_nested_field: NestedSchema | null;
}
export interface ComplexSchema {
  nullable_int_field: number | null;
  nullable_decimal_field: number | null;
  nullable_enum_field: EnumFruit | null;
  nullable_nested_field: NestedSchema | null;
  nested_list_field: Array<NestedSchema>;
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py2ts-0.0.3.tar.gz (6.9 kB view hashes)

Uploaded Source

Built Distribution

py2ts-0.0.3-py3-none-any.whl (7.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page