Skip to content

semohr/py2ts

Repository files navigation

py2ts

TypeScript type definitions from Python type hints

build status docs License: GPL v3

Features

  • Complex Types Support: Handle complex types such as enums and nested typed dictionaries.
  • Comprehensive Documentation: Access detailed documentation, including a Quickstart Guide and API Reference, to help you get started and understand the library's capabilities.

Installation

You can install Py2Ts from git directly using pip:

pip install git+https://github.com/semohr/py2ts.git

Quickstart

To generate TypeScript type definitions from Python type hints, use the generate_ts function from the py2ts.generate module. Here's an example:

from py2ts import generate_ts

class Person:
    name: str
    age: int

print(generate_ts(Person))

This will output the following TypeScript type definition:

export interface Person {
    name: string;
    age: number;
}

Please refer to the Quickstart Guide for more examples and detailed instructions.

Complex Types Support

Py2Ts supports complex types such as enums and nested typed dictionaries. Here's an example:

from __future__ import annotations
from enum import Enum
from typing_extensions import NotRequired
from typing import TypedDict
from py2ts import generate_ts

class Color(Enum):
    RED = 1
    GREEN = "green"
    BLUE = "blue"   

class Polygon(TypedDict):
    color: Color
    edges: NotRequired[int]
    children: list[Polygon] | None

ts = generate_ts(Polygon)

print(ts.full_str())

This will output the following TypeScript type definition:

export enum Color {
	RED = 1,
	GREEN = 'green',
	BLUE = 'blue',
}

export interface Polygon {
	color: Color;
	edges?: number;
	children: Array<Polygon> | null;
}