{"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":"python","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,"search_vec":"'2.0.0':68 'accur':37 'activ':73 'allow':52 'applic':47 'cadenc':75 'cli':7,87 'code':84 'convert':4,10 'current':65 'definit':33,63 'ensur':28 'fastapi':86 'generat':85,89 'interact':49 'interfac':15 'javascript':46 'model':12 'older':25 'polyfil':23 'pydant':1,11,21,80,82 'python':44 'recent':77 'releas':74 'result':31 'scenario':41 'simpl':6 'sinc':50 'singl':57 'sourc':58 'stabl':35 'support':17,79 'tool':8 'truth':60 'type':62,88 'typescript':3,14,32,83 'updat':78 'use':38 'v2':81 'version':19,26,66","created_at":"2026-04-11T09:26:23.028023+00:00","updated_at":"2026-04-16T18:24:16.684003+00:00","problems":[{"fix":"Ensure `pydantic-to-typescript` is installed correctly via pip: `pip install pydantic-to-typescript`. If it's still not found, check your Python environment's script directory and add it to your system's PATH, or try running it with `python -m pydantic_to_typescript`.","cause":"The `pydantic-to-typescript` CLI tool's executable `pydantic2ts` is not found in your system's PATH, usually meaning the package was not installed or its installation directory is not configured correctly.","error":"pydantic2ts: command not found"},{"fix":"Upgrade `pydantic-to-typescript` to version 2.0.0 or greater to ensure Pydantic V2 compatibility: `pip install 'pydantic-to-typescript>=2'`. If you are intentionally using Pydantic V1, ensure your `pydantic-to-typescript` version is compatible with Pydantic V1, or adapt your models to Pydantic V2 syntax.","cause":"This error often occurs when `pydantic-to-typescript` is used with a Pydantic V2 model while an older version of `pydantic-to-typescript` is installed, or when there's an incompatibility in Pydantic versions where 'Config' (from V1) is expected but 'model_config' (from V2) is present, or vice-versa.","error":"AttributeError: 'Config' (when using pydantic-to-typescript)"},{"fix":"Verify the `--module` argument correctly points to your Python file (e.g., `--module ./path/to/your_models.py`) or package (e.g., `--module your_package.your_module`). Ensure your current working directory or `PYTHONPATH` allows Python to import the specified module.","cause":"The `pydantic-to-typescript` tool cannot find the Python module specified with the `--module` argument, usually due to an incorrect file path, an incorrectly formed module name, or the module not being in the Python path.","error":"ModuleNotFoundError: No module named 'your_module_name' (when running pydantic2ts)"},{"fix":"Install `json-schema-to-typescript` globally using npm: `npm install -g json-schema-to-typescript`. Alternatively, if installed locally (e.g., via `yarn`), specify the exact path to the `json2ts` executable using the `--json2ts-cmd` option.","cause":"`pydantic-to-typescript` relies on the `json2ts` (json-schema-to-typescript) Node.js CLI tool, which is not installed or not accessible in your system's PATH.","error":"json2ts: command not found"},{"fix":"Update `pydantic-to-typescript` to its latest version, which should include fixes for `TypeAlias` support: `pip install --upgrade pydantic-to-typescript`. If the issue persists, consider temporarily refactoring your models to avoid `TypeAlias` or checking the official GitHub issues for a workaround specific to your version.","cause":"An older version of `pydantic-to-typescript` has a known bug where it fails to process Pydantic models that include Python's `TypeAlias` type hint.","error":"Error when TypeAlias is used (pydantic-to-typescript)"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"2.0.0","cli_name":"pydantic-to-typescript","cli_version":"sh: 1: pydantic-to-typescript: not found","type":"library","homepage":null,"github":"https://github.com/phillipdupuis/pydantic-to-typescript","docs":null,"changelog":null,"pypi":"https://pypi.org/project/pydantic-to-typescript/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization","web-framework"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-28","next_check":"2026-07-28","install_tag":null}}