{"id":3225,"library":"pydantic-to-typescript","title":"Pydantic to TypeScript Converter","description":"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.","status":"active","version":"2.0.0","language":"en","source_language":"en","source_url":"https://github.com/phillipdupuis/pydantic-to-typescript","tags":["pydantic","typescript","code generation","fastapi","cli","type generation"],"install":[{"cmd":"pip install pydantic-to-typescript","lang":"bash","label":"Install Python package"},{"cmd":"npm install -g json-schema-to-typescript # or yarn global add json-schema-to-typescript","lang":"bash","label":"Install required external tool (json2ts)"}],"dependencies":[{"reason":"Core functionality relies on Pydantic models.","package":"pydantic","optional":false},{"reason":"This is an external Node.js CLI tool that pydantic-to-typescript calls internally to perform the actual TypeScript conversion from generated JSON schemas. It is a mandatory dependency, but not a Python package.","package":"json-schema-to-typescript (json2ts CLI)","optional":false}],"imports":[{"note":"Main function for programmatic conversion.","symbol":"generate_typescript_defs","correct":"from pydantic2ts import generate_typescript_defs"}],"quickstart":{"code":"import os\nfrom pydantic import BaseModel, Field\nfrom typing import List, Optional\nfrom pydantic2ts import generate_typescript_defs\n\n# Create a dummy Python file with Pydantic models\nmodels_file_content = \"\"\"\nfrom pydantic import BaseModel, Field\nfrom typing import List, Optional\n\nclass Address(BaseModel):\n    street: str\n    city: str\n    zip_code: str = Field(alias='zipCode')\n\nclass User(BaseModel):\n    id: int\n    name: str\n    email: Optional[str]\n    addresses: List[Address]\n\"\"\"\n\nwith open(\"my_models.py\", \"w\") as f:\n    f.write(models_file_content)\n\n# Define output path\noutput_ts_file = \"./frontend/apiTypes.ts\"\n\n# Generate TypeScript definitions programmatically\ngenerate_typescript_defs(\n    \"my_models\", # Refers to my_models.py\n    output_ts_file,\n    # You can also exclude models:\n    # exclude=[\"Address\"]\n)\n\n# --- Or via CLI (requires 'pydantic2ts' entrypoint) ---\n# This part is just for demonstration, not meant to be run directly\n# import subprocess\n# cli_command = f\"pydantic2ts --module my_models --output {output_ts_file}\"\n# print(f\"Running CLI command: {cli_command}\")\n# try:\n#     subprocess.run(cli_command, shell=True, check=True)\n#     print(\"TypeScript definitions generated successfully via CLI.\")\n# except subprocess.CalledProcessError as e:\n#     print(f\"CLI command failed: {e}\")\n\nprint(f\"TypeScript definitions written to {output_ts_file}\")\n\n# Clean up dummy file\nos.remove(\"my_models.py\")\n# Optional: Clean up generated TS file if needed\n# os.remove(output_ts_file)\n","lang":"python","description":"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."},"warnings":[{"fix":"Install `json-schema-to-typescript` globally or locally: `npm install -g json-schema-to-typescript` or `yarn global add json-schema-to-typescript`. If installed locally or at a custom path, specify it using the `--json2ts-cmd` CLI option or the `json2ts_cmd` argument in `generate_typescript_defs`.","message":"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.","severity":"breaking","affected_versions":"All versions"},{"fix":"Upgrade `pydantic-to-typescript` to version 2.0.0 or greater: `pip install 'pydantic-to-typescript>=2'`. Ensure your Pydantic version is compatible with your `pydantic-to-typescript` version.","message":"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.","severity":"breaking","affected_versions":"<2.0.0"},{"fix":"When defining Pydantic V2 models, be explicit about required vs. optional fields. Use `Field(default=None)` for truly optional fields that might be absent, or `Optional[T]` if the field is always present but can be `None`. Understand that `Optional[T]` translates to `T | null` in TypeScript, not necessarily `T?`.","message":"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.","severity":"gotcha","affected_versions":"2.0.0 and above (when used with Pydantic V2)"},{"fix":"Update your Pydantic models to use the `model_config` dictionary for configuration settings, following the Pydantic V2 migration guide.","message":"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.","severity":"gotcha","affected_versions":"2.0.0 and above (when used with Pydantic V2)"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}