Registry / serialization / pydantic-to-typescript

pydantic-to-typescript

JSON →
library2.0.0pypypi✓ verified 28d ago

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.

pip install pydantic-to-typescript
INSTALL
IMPORT
SIG · PYDANTIC-TO-TYPESC
P
pydantic-to-typescript
serializationpythonv2.0.0
Install
3.3s avg
Import
354ms
Disk
26MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v2.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.372s · 27.9MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.3s · import 0.336s · 27MB
26MB installed
● package 26MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

generate_typescript_defs
✓ from pydantic2ts import generate_typescript_defs
Main function for programmatic conversion.

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)
pydantic-to-typescript --version
Debug
Known issues
breakingThe 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.
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`.
affects: All versions
breakingPydantic 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.
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.
affects: <2.0.0
gotchaIn 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.
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?`.
affects: 2.0.0 and above (when used with Pydantic V2)
gotchaPydantic 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.
fix
Update your Pydantic models to use the `model_config` dictionary for configuration settings, following the Pydantic V2 migration guide.
affects: 2.0.0 and above (when used with Pydantic V2)
Errors
Common errors & fixes
pydantic2ts: command not found
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.
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`.
AttributeError: 'Config' (when using pydantic-to-typescript)
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.
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.
ModuleNotFoundError: No module named 'your_module_name' (when running pydantic2ts)
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.
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.
json2ts: command not found
`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.
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.
Error when TypeAlias is used (pydantic-to-typescript)
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.
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.
Upgrade
Version history
2.0.0latest on PyPI · released Nov 22, 2024
Audit
Dependencies
pydanticrequiredCore functionality relies on Pydantic models.
json-schema-to-typescript (json2ts CLI)requiredThis 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.
Agent activity
7 hits · last 30 days
node
6
Resources
pydantic-to-typescript — pip install pydantic-to-typescript · libregistry