🚃 Transpile TypeScript types to Python! A TypeScript to Python type transpiler.
MIT License
This project implements a transpiler for creating pyright compatible type declarations automatically from TypeScript code! This is useful in a number of scenarios. For example:
export type Foo = {
type: "foo"
foo: number[]
optional?: string
}
/** DocStrings are supported! */
export type Bar = {
type: "bar"
bar: string
/** nested objects need extra declarations in Python */
nested: {
foo: Foo
}
}
export type FooBarMap = {
[key: string]: Foo | Bar
}
export type TupleType = [string, Foo | Bar, any[]]
from typing_extensions import Any, Dict, List, Literal, NotRequired, Tuple, TypedDict, Union
class Foo(TypedDict):
type: Literal["foo"]
foo: List[float]
optional: NotRequired[str]
class Ts2Py_tliGTOBrDv(TypedDict):
foo: Foo
class Bar(TypedDict):
"""
DocStrings are supported!
"""
type: Literal["bar"]
bar: str
nested: Ts2Py_tliGTOBrDv
"""
nested objects need extra declarations in Python
"""
FooBarMap = Dict[str,Union[Foo,Bar]]
TupleType = Tuple[str,Union[Foo,Bar],List[Any]]
The easiest way to use TypeScript2Python, is to invoke it directly using npx
and pointing it to one (or multiple) source files that export type declarations.
npx typescript2python <path to typescript source>
It will then output the transpiled code to the terminal.
To save the output as a python file, simply pipe the result to the desired destination.
For example npx typescript2python types.ts > types.py
.
TypeScript2Python supports many of TypeScripts type constructs, including:
boolean
, number
, string
, undefined
type X = 42
, type Y = 'test'
{ foo: string }
string | number
boolean[]
{ bar: { foo: string } }
, that will get transpiled into helper dictionaries{ optional?: number }
, that get transpiled to NotRequired[...]
attributes/** this is very useful */
In TypeScript objects, optional values can also be set to undefined
. By default we assume the according Python
type to be non-nullable, but a more closely matching behavior can be achieved using the flag --nullable-optionals
.
This will result in optional entries beeing transpiled as NotRequired[Optional[T]]
instead of NotRequired[T]
.
We currently do not support the following features: