Skip to main content

ts_type generates typescript's type from python code

Project description

It generates typescript's type definitions from python's objects.

Usage

  1. add types to TypeDefinitionGenerator
from dataclasses import dataclass
from typing import Optional, List, Dict

import ts_type as ts


@ts.gen_type
@dataclass
class MyCustomType:
    a: int
    b: Optional[str]
    c: List[str]
    d: Dict[str, int]
  1. call TypeDefinitionGenerator.generate
import ts_type as ts

if __name__ == '__main__':
    ts.generator.generate('output_dir')

Examples

save following code as example.py

from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import TypeVar, Generic, Optional

import ts_type as ts

T = TypeVar('T')


@ts.gen_type
@dataclass
class Article:
    class Type(Enum):
        news = 'news'
        essay = 'essay'

    @dataclass
    class Author:
        id: int
        name: str

    id: int
    type: Type
    title: str
    aurhot: Author
    published_at: datetime


@ts.gen_type
@dataclass
class Pagination(Generic[T]):
    items: list[T]
    next_cursor: Optional[str]


@ts.gen_type
@dataclass
class Response:
    status: int
    articles: Pagination[Article]

run:

import example
example.ts.generator.generate('output_dir')

output: output_dir/example.gen.ts

export type Article = example__Article;

export type Pagination<T> = example__Pagination<T>;

export type Response = example__Response;

type example__Article = {
    "id": number;
    "type": example__Article__Type;
    "title": string;
    "aurhot": example__Article__Author;
    "published_at": string;
};

type example__Article__Type = ("news" | "essay");

type example__Article__Author = {
    "id": number;
    "name": string;
};

type example__Pagination<T> = {
    "items": T[];
    "next_cursor": (string | null);
};

type example__Response = {
    "status": number;
    "articles": example__Pagination<example__Article>;
};

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ts_type-0.1.0.tar.gz (9.1 kB view hashes)

Uploaded Source

Built Distribution

ts_type-0.1.0-py3-none-any.whl (9.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page