Pydantic to TypeScript Converter
A simple CLI tool for converting Pydantic models into TypeScript interfaces. It supports all versions of Pydantic, with polyfills for older versions to ensure that the resulting TypeScript definitions are stable and accurate. Useful for any scenario in which Python and JavaScript applications are interacting, since it allows you to have a single source of truth for type definitions. The current version is 2.0.0, and it has an active release cadence, with recent updates supporting Pydantic V2.
Warnings
- breaking The library relies on the external Node.js CLI tool `json-schema-to-typescript` (command: `json2ts`). This tool *must* be installed separately (e.g., via `npm` or `yarn`) for `pydantic-to-typescript` to function, as it is not a Python dependency.
- breaking Pydantic V2 introduced significant breaking changes. To correctly convert Pydantic V2 models, you must use `pydantic-to-typescript` version 2.0.0 or higher. Older versions of `pydantic-to-typescript` may fail or produce incorrect TypeScript for Pydantic V2 models.
- gotcha In Pydantic V2, the interpretation of `Optional[T]` has changed. It now signifies a *required* field that *allows* a `None` value, rather than an optional field with a default of `None`. This can lead to TypeScript interfaces where fields are not marked as optional (`?`) but rather as `T | null` or just `T` if `None` is explicitly handled elsewhere.
- gotcha Pydantic V2 migrated model configuration from a nested `Config` class to a `model_config` dictionary. While `pydantic-to-typescript` aims for broad compatibility, ensuring your Pydantic models adhere to V2's configuration style (`model_config = {'extra': 'forbid'}`) is best practice to guarantee correct schema generation and subsequent TypeScript conversion.
Install
-
pip install pydantic-to-typescript -
npm install -g json-schema-to-typescript # or yarn global add json-schema-to-typescript
Imports
- generate_typescript_defs
from pydantic2ts import generate_typescript_defs
Quickstart
import os
from pydantic import BaseModel, Field
from typing import List, Optional
from pydantic2ts import generate_typescript_defs
# Create a dummy Python file with Pydantic models
models_file_content = """
from pydantic import BaseModel, Field
from typing import List, Optional
class Address(BaseModel):
street: str
city: str
zip_code: str = Field(alias='zipCode')
class User(BaseModel):
id: int
name: str
email: Optional[str]
addresses: List[Address]
"""
with open("my_models.py", "w") as f:
f.write(models_file_content)
# Define output path
output_ts_file = "./frontend/apiTypes.ts"
# Generate TypeScript definitions programmatically
generate_typescript_defs(
"my_models", # Refers to my_models.py
output_ts_file,
# You can also exclude models:
# exclude=["Address"]
)
# --- Or via CLI (requires 'pydantic2ts' entrypoint) ---
# This part is just for demonstration, not meant to be run directly
# import subprocess
# cli_command = f"pydantic2ts --module my_models --output {output_ts_file}"
# print(f"Running CLI command: {cli_command}")
# try:
# subprocess.run(cli_command, shell=True, check=True)
# print("TypeScript definitions generated successfully via CLI.")
# except subprocess.CalledProcessError as e:
# print(f"CLI command failed: {e}")
print(f"TypeScript definitions written to {output_ts_file}")
# Clean up dummy file
os.remove("my_models.py")
# Optional: Clean up generated TS file if needed
# os.remove(output_ts_file)