### Install ts2python using pip Source: https://github.com/jecki/ts2python/blob/main/docs/index.md Install the ts2python package using Python's package manager. This command requires pip to be available in your environment. ```bash $ pip install ts2python ``` -------------------------------- ### Test Compatibility with Python Versions Source: https://github.com/jecki/ts2python/blob/main/README.md Run the 'test.sh' script to test compatibility with installed Python versions (3.7+). ```bash bash test.sh ``` -------------------------------- ### TypeScript Anonymous Interface with Server Info Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md An example of an anonymous interface containing a nested object for server information. ```typescript interface InitializeResult { capabilities: ServerCapabilities; serverInfo?: { name: string; version?: string; }; } ``` -------------------------------- ### Output AST with XML Serialization Source: https://github.com/jecki/ts2python/blob/main/docs/index.md Use the --target AST and --serialize XML flags to output the Abstract Syntax Tree of a Typescript file in XML format. This can be a starting point for further analysis or transformation. ```bash $ ts2python --target AST --serialize XML interfaces.ts ``` -------------------------------- ### TypeScript Nested Anonymous Interface Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md An example of a nested anonymous interface within TypeScript. ```typescript interface SemanticTokensClientCapabilities { dynamicRegistration?: boolean; requests: { range?: boolean | { }; full?: boolean | { delta?: boolean; }; }; tokenTypes: string[]; tokenModifiers: string[]; formats: TokenFormat[]; overlappingTokenSupport?: boolean; multilineTokenSupport?: boolean; } ``` -------------------------------- ### TypeScript Anonymous Interface Definition Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Example of an anonymous interface in TypeScript with various field types. ```typescript interface InitializeParams extends WorkDoneProgressParams { processId: integer | null; clientInfo?: { name: string; version?: string; }; locale?: string; rootPath?: string | null; rootUri: DocumentUri | null; initializationOptions?: any; capabilities: ClientCapabilities; trace?: TraceValue; workspaceFolders?: WorkspaceFolder[] | null; } ``` -------------------------------- ### Generic Interface to Generic TypedDict (Python < 3.11) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Generic TypeScript interfaces are transpiled to generic TypedDicts. This example shows the backward-compatible form for Python 3.7+. ```typescript interface ProgressParams { token: ProgressToken; value: T; } ``` -------------------------------- ### TypeScript Union Type for Anonymous Interface Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Example of a TypeScript type that is a union of two anonymous interfaces. ```typescript export type TextDocumentContentChangeEvent = { range: Range; rangeLength?: uinteger; text: string; } | { text: string; }; ``` -------------------------------- ### TypeScript Namespace to Python Enum Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript namespaces containing only constant definitions are transpiled into Python Enums. This example shows a DiagnosticSeverity namespace. ```typescript export namespace DiagnosticSeverity { export const Error: 1 = 1; export const Warning: 2 = 2; export const Information: 3 = 3; export const Hint: 4 = 4; } ``` -------------------------------- ### TypeScript Type Alias to Python Type Assignment (Python 3.7+) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript type aliases are mapped to plain type assignments in Python for compatibility down to version 3.7. This example shows a ProviderResult type. ```typescript type ProviderResult = T | undefined | null | Thenable; ``` -------------------------------- ### Handle Missing and Unexpected Fields with type_check Source: https://github.com/jecki/ts2python/blob/main/docs/Validation.md The `type_check` decorator and `validate_type` function enforce constraints on required fields and reject superfluous fields within TypedDicts. This example demonstrates validation for a `Car` TypedDict with a `NotRequired` field. ```python from ts2python.json_validation import TypedDict, type_check, NotRequired class Car(TypedDict, total=True): brand: str speed: int color: NotRequired[str] @type_check def print_car(car: Car): print('brand: ', car['brand']) print('speed: ', car['speed']) if 'color' in car: print('color: ', car['color']) print_car({'brand': 'Mercedes', 'speed': 200}) print_car({'brand': 'BMW', 'speed': 180, 'color': 'blue'}) try: print_car({'speed': 200}) except TypeError as e: print(e) try: print_car({'brand': 'Mercedes', 'speed': 200, 'PS': 120}) except TypeError as e: print(e) ``` -------------------------------- ### Run Demo Script Source: https://github.com/jecki/ts2python/blob/main/README.md Execute the 'demo.sh' script to see a demonstration of TypeScript interfaces transpiled to Python code. ```bash bash demo.sh ``` -------------------------------- ### Run Unit and Doctests Source: https://github.com/jecki/ts2python/blob/main/README.md Navigate to the 'tests' directory and execute the 'runner.py' script to run all tests. ```bash $ cd tests $ python runner.py ``` -------------------------------- ### Run Grammar Test Source: https://github.com/jecki/ts2python/blob/main/README.md Execute 'tst_ts2python_grammar.py' to perform grammar tests and check reports in the 'REPORT' subdirectory. ```bash python tst_ts2python_grammar.py ``` -------------------------------- ### Python TypedDict Mapping for Nested Interface Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python mapping for the nested SemanticTokensClientCapabilities interface, demonstrating nested TypedDicts. ```python class SemanticTokensClientCapabilities(TypedDict): class Requests_(TypedDict): class Range_1(TypedDict): pass class Full_1(TypedDict): delta: NotRequired[bool] range: NotRequired[Union[bool, Range_1]] full: NotRequired[Union[bool, Full_1]] dynamicRegistration: NotRequired[bool] requests: Requests_ tokenTypes: List[str] tokenModifiers: List[str] formats: List['TokenFormat'] overlappingTokenSupport: NotRequired[bool] multilineTokenSupport: NotRequired[bool] ``` -------------------------------- ### Python Functional TypedDict Mapping for Server Info Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python mapping using the 'functional' syntax for anonymous interfaces, employing TypedDict with a string name. ```python class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[TypedDict("ServerInfo_0", {"name": str, "version": NotRequired[str]})] ``` -------------------------------- ### Generate Type Checker Friendly Python Code Source: https://github.com/jecki/ts2python/blob/main/README.md Employ the `-a toplevel` switch along with `--compatibility` to generate Python code that is more compliant with strict type checkers like mypy or pylance. ```bash $ ts2python --compatibility 3.11 -a toplevel interfaces.ts ``` -------------------------------- ### Python Top-Level TypedDict Mapping for Server Info Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python mapping using the 'toplevel' syntax, defining nested anonymous interfaces as separate top-level classes to avoid type-checker complaints. ```python class InitializeResult_ServerInfo_0(TypedDict): name: str version: NotRequired[str] class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[InitializeResult_ServerInfo_0] ``` -------------------------------- ### TypeScript Interface with Optional Fields (PEP 655 Mode) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Illustrates the mapping for interfaces with optional fields when targeting Python 3.11+ or using the PEP 655 compatibility mode, where `NotRequired` is used directly and `total` remains `True`. ```python class RequestMessage(Message, TypedDict): id: Union[int, str] method: str params: NotRequired[List | Dict] ``` -------------------------------- ### Specify Python compatibility version for generated code Source: https://github.com/jecki/ts2python/blob/main/docs/index.md Use the --compatibility flag with the ts2python command to generate code compatible with a specific Python version. This can result in cleaner code and access to newer Python features. ```bash $ ts2python --compatibility 3.11 [FILENAME.ts] ``` -------------------------------- ### Call ts2python Parser Directly from Python (Method 2) Source: https://github.com/jecki/ts2python/blob/main/README.md Utilize `compile_src` and `serialize_result` from `ts2pthon.ts2pythonParser` for more granular control over parsing and result serialization in Python. ```python from ts2pthon.ts2pythonParser import compile_src, serialize_result ... result, errors = compile_src(DOCUMENT) if errors: for e in errors: print(e) else: print(serialize_result(result)) ``` -------------------------------- ### Import Generated Python TypedDicts Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md After generating the Python file, import the TypedDict classes into your Python code. This allows you to use the generated types for static analysis and runtime checks. ```python from interfaces import * ``` -------------------------------- ### Clone ts2python Repository Source: https://github.com/jecki/ts2python/blob/main/README.md Clone the ts2python repository from GitHub to access its tests and code. ```bash $ git clone https://github.com/jecki/ts2python ``` -------------------------------- ### TypeScript Interface to Python Class Mapping Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Demonstrates the basic conversion of a TypeScript interface to a Python TypedDict class. This is the default mapping behavior for interfaces. ```typescript interface Message { jsonrpc: string; } ``` ```python class Message(TypedDict): jsonrpc: str ``` -------------------------------- ### TypeScript Interfaces to Python TypedDict Conversion Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Illustrates the direct transformation of TypeScript interface definitions into Python TypedDict classes. This conversion facilitates the use of Python's typing system for data structures defined in TypeScript. ```typescript interface Message { jsonrpc: string; } interface RequestMessage extends Message { id: integer | string; method: string; params?: array | object; } interface ResponseMessage extends Message { id: integer | string | null; result?: string | number | boolean | object | null; error?: ResponseError; } ``` -------------------------------- ### Python type statement for ProviderResult (Python 3.12+) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python 3.12 and later versions utilize the 'type' statement (PEP 695) for defining type aliases, offering a more elegant syntax. ```python type ProviderResult[T] = T | None | Coroutine[T | None] ``` -------------------------------- ### Python TypedDict Mapping for InitializeParams Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md The default Python mapping of the TypeScript InitializeParams interface using local TypedDict classes. ```python class InitializeParams(WorkDoneProgressParams, TypedDict): class ClientInfo_(TypedDict): name: str version: NotRequired[str] processId: Union[int, None] clientInfo: NotRequired[ClientInfo_] locale: NotRequired[str] rootPath: NotRequired[Union[str, None]] rootUri: Union['DocumentUri', None] initializationOptions: NotRequired[Any] capabilities: 'ClientCapabilities' trace: NotRequired['TraceValue'] workspaceFolders: NoRequired[Union[List['WorkspaceFolder'], None]] ``` -------------------------------- ### Generic TypedDict (Python 3.12+) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python 3.12 and later versions support a more direct syntax for generic TypedDict classes. ```python class ProgressParams[T](TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### Runtime Type Validation with validate_type Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Demonstrates how to use the `validate_type` function from `ts2python.json_validation` to perform runtime type checking on Python objects against their annotated types. This is crucial when data originates from external sources like JSON. ```python import json from ts2python.json_validation import validate_type # Assuming input_data is a JSON string request_msg: RequestMessage = json.loads(input_data) validate_type(request_msg, RequestMessage) ``` -------------------------------- ### Map TypeScript Records to Python Dictionaries Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript Records are mapped to parameterized Python dictionaries. ```typescript export interface Test { t: Record } ``` ```python class Test(TypedDict): t: Dict[str, float] ``` -------------------------------- ### Call ts2python Parser Directly from Python (Method 1) Source: https://github.com/jecki/ts2python/blob/main/README.md Use the `process_file` function from `ts2python.ts2pthonParser` to convert TypeScript files to Python files directly within a Python script. ```python from ts2python.ts2pthonParser import process_file ... process_file("SOURCE.ts", "DESTINATION.py") ``` -------------------------------- ### Resulting Python Enum Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md The Python equivalent of the DiagnosticSeverity TypeScript namespace, demonstrating the mapping to an IntEnum class. ```python class DiagnosticSeverity(IntEnum): Error = 1 Warning = 2 Information = 3 Hint = 4 ``` -------------------------------- ### TypeScript Interface with Optional Fields to Python TypedDict Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Shows how TypeScript interfaces with optional fields are mapped to Python TypedDicts, including compatibility adjustments for older Python versions (pre-3.11) using `NotRequired` and `total=False`. ```typescript interface RequestMessage extends Message { id: integer | string; method: string; params?: array | object; } ``` ```python NotRequired = Optional class RequestMessage(Message, TypedDict, total=False): id: Union[int, str] method: str params: NotRequired[Union[List, Dict]] ``` -------------------------------- ### Generated Python TypedDict Classes Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Shows the Python TypedDict classes generated from the provided TypeScript interfaces. These classes mirror the structure and types of their TypeScript counterparts, enabling Pythonic type hinting. ```python class Message(TypedDict, total=True): jsonrpc: str class RequestMessage(Message, TypedDict): id: Union[int, str] method: str params: NotRequired[Union[List, Dict]] class ResponseMessage(Message, TypedDict): id: Union[int, str, None] result: NotRequired[Union[str, float, bool, Dict, None]] error: NotRequired['ResponseError'] ``` -------------------------------- ### Generate Python TypedDicts from TypeScript Interfaces Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Run the ts2python command-line tool on your TypeScript interface definitions to generate corresponding Python TypedDict classes. This is useful for maintaining type consistency between frontend and backend code. ```bash $ ts2python interfaces.ts ``` -------------------------------- ### Python Type Alias with TypeAlias (Python 3.10+) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md For Python 3.10 and above, type assignments are annotated with TypeAlias, leveraging PEPs 586, 604, and 613. ```python T = TypeVar('T') ProviderResult: TypeAlias = T | None | Coroutine[T | None] ``` -------------------------------- ### Map TypeScript Index Signatures to Python Dictionaries Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript index signatures are transpiled to Python dictionaries, with the index signature identifier being dropped. ```typescript export interface WorkspaceEdit { changes?: { [uri: DocumentUri]: TextEdit[]; }; documentChanges?: ( TextDocumentEdit[] | (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[] ); changeAnnotations?: { [id: string /* ChangeAnnotation Identifier */]: ChangeAnnotation; }; } ``` ```python class WorkspaceEdit(TypedDict, total=False): changes: NotRequired[Dict['DocumentUri', List['TextEdit']]] documentChanges: Union[ List['TextDocumentEdit'], List[Union['TextDocumentEdit', 'CreateFile', 'RenameFile', 'DeleteFile']], None] changeAnnotations: NotRequired[Dict[str, 'ChangeAnnotation']] ``` -------------------------------- ### Type-Annotated Function for Request Processing Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Defines a Python function with type annotations for its input and return values, using the generated TypedDicts. This enables static type checking with tools like mypy. ```python def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### Python Type Assignment for ProviderResult Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md The Python equivalent of the ProviderResult TypeScript type alias, mapping undefined and null to None and resolving redundancies. ```python T = TypeVar('T') ProviderResult = Union[T, None, Coroutine[Union[T, None]]] ``` -------------------------------- ### Deserialize JSON data into a TypedDict object Source: https://github.com/jecki/ts2python/blob/main/docs/index.md Deserialize a JSON string into a Python TypedDict object using the `json.loads` function. Ensure the root type of the JSON data is known beforehand to correctly deserialize it. ```python import json request_msg: RequestMessage = json.loads(input_data) ``` -------------------------------- ### Generic TypedDict (Python < 3.11) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md The Python representation of a generic TypeScript interface for compatibility with Python versions prior to 3.11, using Generic and GenericTypedDict. ```python T = TypeVar('T') class ProgressParams(Generic[T], GenericTypedDict, total=True): token: 'ProgressToken' value: T ``` -------------------------------- ### Python TypedDict Mapping for Union Type Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Python mapping for a union of anonymous interfaces, resulting in numbered local classes and a Union type. ```python class TextDocumentContentChangeEvent_0(TypedDict, total=False): range: Range rangeLength: NotRequired[int] text: str class TextDocumentContentChangeEvent_1(TypedDict): text: str TextDocumentContentChangeEvent = Union[ TextDocumentContentChangeEvent_0, TextDocumentContentChangeEvent_1] ``` -------------------------------- ### Generic TypedDict (Python 3.11+) Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md For Python 3.11 and above, generic typed dicts can be defined using only TypeVar, without inheriting from Generic or GenericTypedDict. ```python T = TypeVar('T') class ProgressParams(TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### TypeScript Literal Type to Python Literal Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md Demonstrates the conversion of a TypeScript literal union type to a Python `Literal` type. For Python versions below 3.8, `typing_extensions` is required for the `Literal` type. ```typescript export type ResourceOperationKind = 'create' | 'rename' | 'delete'; ``` ```python ResourceOperationKind = Literal['create', 'rename', 'delete'] ``` -------------------------------- ### Validate a Value Against a TypedDict with validate_type Function Source: https://github.com/jecki/ts2python/blob/main/docs/Validation.md Explicitly validate a given value against a specified TypedDict type using the `validate_type` function. This function raises a `TypeError` if the value does not conform to the expected type, including checks for missing or unexpected fields. ```python from ts2python.json_validation import validate_type, TypedDict, NotRequired class Position(TypedDict, total=True): line: int character: int validate_type({'line': 42, 'character': 11}, Position) try: validate_type({'line': 42, 'character': "bad mistake"}, Position) except TypeError as e: print(e) ``` -------------------------------- ### Map TypeScript Enum with String Keys to Python IntEnum Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript enums with string keys that are valid identifiers are mapped to Python IntEnums using enum.auto(). ```typescript export enum MilkyWay { 'from the earth', 'past the moon', 'to the stars' } ``` ```python class MilkyWay(IntEnum): earth = enum.auto() moon = enum.auto() stars = enum.auto() ``` -------------------------------- ### Runtime Type Validation with type_check Decorator Source: https://github.com/jecki/ts2python/blob/main/docs/BasicUsage.md Applies the `type_check` decorator from `ts2python.json_validation` to a function to automatically validate its input parameters and return value against their type annotations at runtime. This is useful for ensuring data integrity during function calls. ```python from ts2python.json_validation import type_check @type_check def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### Validate Function Arguments and Return Values with type_check Decorator Source: https://github.com/jecki/ts2python/blob/main/docs/Validation.md Use the `type_check` decorator to automatically validate function arguments and return values against their TypedDict type annotations. Ensure that your TypedDict classes inherit from `ts2python.json_validation.TypedDict` for correct runtime behavior. ```python from ts2python.json_validation import TypedDict, type_check class Position(TypedDict, total=True): line: int character: int class Range(TypedDict, total=True): start: Position end: Position @type_check def line_too_long(rng: Range) -> bool: return (rng['start']['character'] > 255 or rng['end']['character'] > 255) print(line_too_long({'start': {'line': 1, 'character': 1}, 'end': {'line': 8, 'character': 17}})) try: line_too_long({'start': {'line': 1, 'character': 1}, 'end': 256}) except TypeError as e: print(e) ``` -------------------------------- ### Map TypeScript Tuple Types to Python Tuple Types Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript tuple types are transpiled to Python tuple types, preserving the union of types. ```typescript export interface ParameterInformation { label: string | [uinteger, uinteger]; documentation?: string | MarkupContent; } ``` ```python class ParameterInformation(TypedDict): label: Union[str, Tuple[int, int]] documentation: NotRequired[Union[str, 'MarkupContent']] ``` -------------------------------- ### Map TypeScript Enum to Python Enum Source: https://github.com/jecki/ts2python/blob/main/docs/Mapping.md TypeScript enums with string values are mapped to Python Enums. Ensure the string values are valid Python identifiers. ```typescript export enum FoldingRangeKind { Comment = 'comment', Imports = 'imports', Region = 'region' } ``` ```python class FoldingRangeKind(Enum): Comment = 'comment' Imports = 'imports' Region = 'region' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.