ts2python Documentation

ts2python is a transpiler that converts TypeScript interfaces to Python records like TypedDict and provides runtime json-validation against those interfaces/TypedDicts.

(In the future also other record structures like pydantic or attr might be supported by ts2python as well.)

ts2python is licensed under the Apache-2.0 open source license. The source code can be cloned freely from: https://github.com/jecki/ts2python

ts2python can be installed as usual with Python’s package-manager “pip”:

$ pip install ts2python

ts2python requires at least Python Version 3.6. The only dependency of ts2python is the parser-generator DHParser. For Python versions below 3.8 installing the typing_extensions is highly recommended, though.

Alternatively, you can just download the script ts2PythonParser.py for converting Typescript source code consisting to interface definitions to Python modules from the git-repository which runs without installing ts2python as long as DHParser has been installed. Or, if you just interested in runtime type validation, you can just copy the module json_validation from the git repository, which merely requires the typing_extensions to be present.

Generating Python pendants for typescript interfaces is as simple as calling:

$ ts2python interfaces.ts

and then importing the generated interfaces.py by:

from interfaces import *

For every typescript interface in the interfaces.ts file the generated Python module contains a TypedDict-class with the same name that defines the same data structure as the typescript interface. Typescript data serialized as json can simply be deserialized by Python-code as long as you know the type of the root data structure beforehand, e.g.:

import json
request_msg: RequestMessage = json.loads(input_data)

The only requirement is that the root type of the json data is known beforehand. Everything else simply falls into place.

Current Limitations

Presently, ts2python is mostly limited to Typescript-Interfaces that do not contain any methods. The language server-protocol-definitions can be transpiled successfully.

However, as of now, most Typescript-header files, i.e. the files ending with “.d.ts” cannot be transpiled, because support for function headers, classes and interfaces with methods, ambient modules and namespaces is still incomplete. This will be added in the future.

Indices and tables