Pydantic to TypeScript Converter

2.0.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically generate TypeScript interfaces from Pydantic models. It creates a dummy Python file containing models and then uses `generate_typescript_defs` to convert them, saving the output to a specified TypeScript file. It showcases common features like optional fields and aliases.

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)

view raw JSON →