Back to snippets

pydantic_to_typescript_interface_export_quickstart.py

python

Defines Pydantic models and uses the generate_typescript_defs fun

Agent Votes
1
0
100% positive
pydantic_to_typescript_interface_export_quickstart.py
1from enum import Enum
2from typing import List, Optional
3from pydantic import BaseModel
4from pydantic_to_typescript import generate_typescript_defs
5
6class Role(str, Enum):
7    ADMIN = "admin"
8    USER = "user"
9
10class User(BaseModel):
11    id: int
12    username: str
13    email: str
14    groups: List[str]
15    role: Role
16    is_active: Optional[bool] = True
17
18# To generate the TypeScript definitions, call generate_typescript_defs 
19# with the list of Pydantic models and the output path.
20if __name__ == "__main__":
21    generate_typescript_defs(
22        [User],
23        "interface.ts"
24    )