### Install ts2python Source: https://ts2python.readthedocs.io/en/latest/index.html Install ts2python using pip. This command installs the package and its dependencies. ```bash $ pip install ts2python ``` -------------------------------- ### TypeScript Anonymous Interface: InitializeParams Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Example of an anonymous interface in TypeScript. ```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; } ``` -------------------------------- ### Output AST with XML Serialization Source: https://ts2python.readthedocs.io/en/latest/index.html Use the `--target AST` and `--serialize XML` command-line switches to output the Abstract Syntax Tree of a TypeScript file in XML format. This can be a starting point for custom transformations. ```bash $ ts2python --target AST --serialize XML interfaces.ts ``` -------------------------------- ### TypeScript Anonymous Interface: SemanticTokensClientCapabilities Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Example of a nested anonymous interface in 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: InitializeResult Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Example of an anonymous interface in TypeScript for InitializeResult. ```typescript interface InitializeResult { capabilities: ServerCapabilities; serverInfo?: { name: string; version?: string; }; } ``` -------------------------------- ### TypeScript Interface Definitions Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html Example TypeScript interfaces that will be converted into Python TypedDict classes. These define the structure and types of data exchanged, often in JSON-RPC communication. ```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; } ``` -------------------------------- ### TypeScript Enum with String Keys to Python IntEnum Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Demonstrates how TypeScript enums with string keys that are valid identifiers are converted to Python IntEnums. Note that Python enums start counting from 1. ```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() ``` -------------------------------- ### Generic Interface to Generic TypedDict (Python 3.7+) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Generic interfaces in TypeScript are transpiled to generic typed dicts. This example shows the backward-compatible form for Python 3.7 and above. ```typescript interface ProgressParams { token: ProgressToken; value: T; } ``` ```python T = TypeVar('T') class ProgressParams(Generic[T], GenericTypedDict, total=True): token: 'ProgressToken' value: T ``` -------------------------------- ### TypeScript Type Union: TextDocumentContentChangeEvent Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Example of a type union in TypeScript representing an anonymous interface. ```typescript export type TextDocumentContentChangeEvent = { range: Range; rangeLength?: uinteger; text: string; } | { text: string; }; ``` -------------------------------- ### TypeScript Namespace to Python Enum Source: https://ts2python.readthedocs.io/en/latest/Mapping.html TypeScript namespaces consisting entirely of constant definitions are transpiled to Python Enums. This example shows the conversion of 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; } ``` ```python class DiagnosticSeverity(IntEnum): Error = 1 Warning = 2 Information = 3 Hint = 4 ``` -------------------------------- ### TypeScript Import Statement Source: https://ts2python.readthedocs.io/en/latest/Mapping.html TypeScript import statements are parsed and ignored by ts2python starting from version 0.6.9 to prevent parser errors. ```typescript import {ChangeInfo, CommentRange} from './rest-api'; ``` -------------------------------- ### TypeScript Enum to Python IntEnum Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt TypeScript enums with quoted string members are converted to Python IntEnums. Python enums start counting from 1. ```typescript enum MilkyWay { 'earth', 'moon', 'stars' } ``` -------------------------------- ### Python Mapping of InitializeResult (Toplevel Syntax) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python equivalent of InitializeResult using toplevel syntax to avoid nested classes. ```python class InitializeResult_ServerInfo_0(TypedDict): name: str version: NotRequired[str] class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[InitializeResult_ServerInfo_0] ``` -------------------------------- ### Mapping Anonymous Interface to Python TypedDict (Type Syntax) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Illustrates the experimental 'type'-syntax for rendering anonymous interfaces directly as TypedDict. ```python TypedDict[{"name": str, "version": NotRequired[str]}] ``` -------------------------------- ### Generate Python code with specific version compatibility Source: https://ts2python.readthedocs.io/en/latest/index.html Use the --compatibility flag to generate Python code compatible with specific Python versions. This can result in cleaner code and access to newer language features. ```bash $ ts2python --compatibility 3.11 [FILENAME.ts] ``` -------------------------------- ### Python Mapping of InitializeResult (Functional Syntax) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python equivalent of InitializeResult using functional syntax for anonymous interfaces. ```python class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[TypedDict("ServerInfo_0", {"name": str, "version": NotRequired[str]}) ] ``` -------------------------------- ### Type Hinting for Function Arguments and Return Values Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html Use type annotations in your Python functions to enable static type checking with tools like mypy. This improves code readability and helps catch errors early. ```python def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### Python Mapping of SemanticTokensClientCapabilities Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python equivalent of the TypeScript SemanticTokensClientCapabilities interface with nested TypedDict. ```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] ``` -------------------------------- ### Mapping Generic TypeScript Interface to Python Generic TypedDict (Python 3.12+) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Demonstrates the transpilation of a generic TypeScript interface to a Python generic TypedDict class, for Python 3.12 and above. ```python class ProgressParams[T](TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### Mapping Generic TypeScript Interface to Python Generic TypedDict (Python 3.7+) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Illustrates the transpilation of a generic TypeScript interface to a Python GenericTypedDict, compatible with Python 3.7 and above. ```typescript interface ProgressParams { token: ProgressToken; value: T; } ``` ```python T = TypeVar('T') class ProgressParams(Generic[T], GenericTypedDict, total=True): token: 'ProgressToken' value: T ``` -------------------------------- ### TypeScript Interfaces to Python TypedDicts Source: https://ts2python.readthedocs.io/en/latest/_sources/BasicUsage.rst.txt Illustrates the direct transformation of TypeScript interfaces into their corresponding Python TypedDict representations, including handling of unions, optional properties, and inheritance. ```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; } ``` -------------------------------- ### Import Generated TypedDict Classes Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html After generating the Python file, you can import the TypedDict classes directly into your Python code. This allows you to use them for type hinting and static analysis. ```python from interfaces import * ``` -------------------------------- ### Generate Python from TypeScript Interface Source: https://ts2python.readthedocs.io/en/latest/_sources/index.rst.txt Transpile TypeScript interfaces to Python TypedDicts from the command line. The generated Python module can then be imported. ```bash $ ts2python interfaces.ts ``` ```python from interfaces import * ``` -------------------------------- ### Python Type Alias with PEP 695 Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Demonstrates the use of the `type` statement for creating type aliases, introduced in Python 3.12 and supported by ts2Python for compatibility levels 3.12 and above. This syntax is considered an elegant way to define type aliases. ```python type ProviderResult[T] = T | None | Coroutine[T | None] ``` -------------------------------- ### Python Mapping of InitializeParams Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python equivalent 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]] ``` -------------------------------- ### Mapping TypeScript Type Union to Python TypedDict and Union Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Demonstrates how a TypeScript type union with optional fields is converted into separate Python TypedDict classes and a Union type. ```typescript export type TextDocumentContentChangeEvent = { range: Range; rangeLength?: uinteger; text: string; } | { text: string; }; ``` ```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] ``` -------------------------------- ### Mapping Anonymous Interface to Python TypedDict (Toplevel Syntax) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Demonstrates the '--anonymous toplevel' option for avoiding nested class definitions by rendering anonymous interfaces as separate top-level TypedDict classes. ```python class InitializeResult_ServerInfo_0(TypedDict): name: str version: NotRequired[str] class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[InitializeResult_ServerInfo_0] ``` -------------------------------- ### Set TypeScript to Python Transpiler Compatibility Version Source: https://ts2python.readthedocs.io/en/latest/_sources/index.rst.txt Generate Python code compatible with a specific Python version using the --compatibility flag. This can result in cleaner code and access to newer Python features. ```bash $ ts2python --compatibility 3.11 [FILENAME.ts] ``` -------------------------------- ### Mapping TypeScript Namespace with Constants to Python Enum Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Shows how a TypeScript namespace containing only constant definitions is transpiled into a Python IntEnum. ```typescript export namespace DiagnosticSeverity { export const Error: 1 = 1; export const Warning: 2 = 2; export const Information: 3 = 3; export const Hint: 4 = 4; } ``` ```python class DiagnosticSeverity(IntEnum): Error = 1 Warning = 2 Information = 3 Hint = 4 ``` -------------------------------- ### TypeScript Interface with Optional Fields (PEP 655 Mode) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Mapping of a TypeScript interface with optional fields to a Python TypedDict, enforcing PEP 655 compatibility for Python 3.11+. `NotRequired` is used directly, and `total` defaults to `True`. ```python class RequestMessage(Message, TypedDict): id: Union[int, str] method: str params: NotRequired[List | Dict] ``` -------------------------------- ### Mapping TypeScript Type Alias to Python TypeAlias (Python 3.10+) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Illustrates the mapping of a TypeScript type alias to a Python type assignment annotated with TypeAlias, leveraging Python 3.10+ features. ```python T = TypeVar('T') ProviderResult: TypeAlias = T | None | Coroutine[T | None] ``` -------------------------------- ### Mapping Anonymous Interface to Python TypedDict (Functional Syntax) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Shows the transpilation of an anonymous nested interface within a TypeScript interface to a Python TypedDict using functional syntax. ```typescript interface InitializeResult { capabilities: ServerCapabilities; serverInfo?: { name: string; version?: string; }; } ``` ```python class InitializeResult(TypedDict): capabilities: 'ServerCapabilities' serverInfo: NotRequired[TypedDict("ServerInfo_0", {"name": str, "version": NotRequired[str]})] ``` -------------------------------- ### Runtime Type Validation with JSON Parsing Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html When data originates from external sources like JSON, runtime type validation is crucial. Use `json.loads` to deserialize and then `validate_type` to ensure conformance with the expected TypedDict structure. ```python import json request_msg: RequestMessage = json.loads(input_data) ``` ```python from ts2python.json_validation import validate_type validate_type(request_msg, RequestMessage) ``` -------------------------------- ### Mapping Generic TypeScript Interface to Python Generic TypedDict (Python 3.11+) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Shows the transpilation of a generic TypeScript interface to a Python TypedDict using TypeVars, suitable for Python 3.11 and above. ```python T = TypeVar('T') class ProgressParams(TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### TypeScript Interface with Optional Fields to Python TypedDict (Compatibility Mode) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Mapping of a TypeScript interface with optional fields to a Python TypedDict in compatibility mode (Python < 3.11). Optional fields are mapped using NotRequired, and the TypedDict is marked with 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]] ``` -------------------------------- ### Type-Annotated Function for Static Type-Checking Source: https://ts2python.readthedocs.io/en/latest/_sources/BasicUsage.rst.txt Define Python functions with type annotations for request and response messages to enable static type-checking with tools like mypy. ```python def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### TypeScript Interface with Optional Fields to Python TypedDict (PEP 655 Mode) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Mapping of a TypeScript interface with optional fields to a Python TypedDict when enforcing PEP 655 (Python >= 3.11). Optional fields are mapped using NotRequired, and the TypedDict retains its default total=True. ```typescript interface RequestMessage extends Message { id: integer | string; method: string; params?: array | object; } ``` ```python class RequestMessage(Message, TypedDict): id: Union[int, str] method: str params: NotRequired[List | Dict] ``` -------------------------------- ### TypeScript Record to Python Dictionary Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Maps TypeScript Records to parameterized Python dictionaries. Note that `Record` is mapped to `Dict[str, float]`. ```typescript export interface Test { t: Record } ``` ```python class Test(TypedDict): t: Dict[str, float] ``` -------------------------------- ### Mapping TypeScript Type Alias to Python Type Assignment (Python 3.7+) Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Shows how a TypeScript type alias involving unions and undefined/null is mapped to a Python Union type assignment, compatible with Python 3.7. ```typescript type ProviderResult = T | undefined | null | Thenable; ``` ```python T = TypeVar('T') ProviderResult = Union[T, None, Coroutine[Union[T, None]]] ``` -------------------------------- ### Generate Python TypedDicts from TypeScript Interfaces Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html 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 ``` -------------------------------- ### Control ts2python Parser Output with Version Flag Source: https://ts2python.readthedocs.io/en/latest/_sources/index.rst.txt Specify the target Python version for the generated code using the -c flag. This influences the compatibility and features used in the output. ```bash * -c" followed by a Python Version-number, e.g. ``-c 3.12`` ``` -------------------------------- ### TypeScript Index Signatures to Python TypedDict Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Index signatures in TypeScript interfaces are transpiled to dictionaries within Python TypedDicts. ```typescript export interface WorkspaceEdit { changes?: { [uri: DocumentUri]: TextEdit[]; }; documentChanges?: ( TextDocumentEdit[] | (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[] ); changeAnnotations?: { [id: string /* ChangeAnnotationIdentifier */]: ChangeAnnotation; }; } ``` -------------------------------- ### Control ts2python Parser Output with PEP Flags Source: https://ts2python.readthedocs.io/en/latest/_sources/index.rst.txt Specify supported PEP numbers using the -p flag to control features like Enums in the generated Python code. Supported PEPs include 435. ```bash * ``-p`` followed by a comma separated list of `PEP`_-numbers, e.g. ``-p 563,601``. Supported PEPs are: * `435`_ - use Enums (Python 3.4) ``` -------------------------------- ### Generic Interface to TypedDict (Python 3.11+) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html For Python 3.11 and above, generic typed dicts can be simplified using TypeVars without needing to derive from Generic or GenericTypedDict. ```typescript interface ProgressParams { token: ProgressToken; value: T; } ``` ```python T = TypeVar('T') class ProgressParams(TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### Generic Interface to Generic TypedDict (Python 3.12+) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python versions higher than 3.12 support a direct generic TypedDict class syntax. ```typescript interface ProgressParams { token: ProgressToken; value: T; } ``` ```python class ProgressParams[T](TypedDict): token: 'ProgressToken' value: T ``` -------------------------------- ### Python Mapping of TextDocumentContentChangeEvent Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Python equivalent of the TypeScript TextDocumentContentChangeEvent type union using numbered local TypedDict classes. ```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] ``` -------------------------------- ### Python TypedDicts Generated from TypeScript Source: https://ts2python.readthedocs.io/en/latest/_sources/BasicUsage.rst.txt The Python code generated from the TypeScript interfaces above, defining TypedDict classes with appropriate type hints for static analysis. ```python from typing import List, Dict, Union, NotRequired 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'] ``` -------------------------------- ### Validate Uniform Sequence Items Source: https://ts2python.readthedocs.io/en/latest/Validation.html Use validate_uniform_sequence to ensure all items in a given sequence are of the same specified type. This is helpful for maintaining data consistency in collections. ```python validate_uniform_sequence((1, 5, 3), int) try: validate_uniform_sequence(['a', 'b', 3], str) except TypeError as e: print(e) ``` -------------------------------- ### TypeScript Type Alias to Python Type Statement (Python 3.12+) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Compatibility levels of 3.12 and above support PEP 695, using the elegant 'type' statement syntax. ```typescript type ProviderResult = T | undefined | null | Thenable; ``` ```python type ProviderResult[T] = T | None | Coroutine[T | None] ``` -------------------------------- ### TypeScript Interface to Python TypedDict Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Basic mapping of a TypeScript interface to a Python class inheriting from TypedDict. ```typescript interface Message { jsonrpc: string; } ``` ```python class Message(TypedDict): jsonrpc: str ``` -------------------------------- ### TypeScript Index Signature to Python Dictionary Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Transpiles TypeScript index signatures to Python dictionaries, dropping the index signature identifier. Note the use of `NotRequired` and `Union` for optional and complex types. ```typescript export interface WorkspaceEdit { changes?: { [uri: DocumentUri]: TextEdit[]; }; documentChanges?: ( TextDocumentEdit[] | (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[] ); changeAnnotations?: { [id: string /* ChangeAnnotationIdentifier */]: 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']] ``` -------------------------------- ### validate_uniform_sequence function Source: https://ts2python.readthedocs.io/en/latest/Validation.html Ensures that every item in a given sequence is of the same specified type. It raises a TypeError if any item in the sequence does not match the expected item type. ```APIDOC ## Function: validate_uniform_sequence ### Description Ensures that every item in a given sequence is of the same particular type. ### Parameters * **sequence** (Iterable) - An iterable to be validated. * **item_type** (Type) - The expected type of all items in the iterable sequence. ``` -------------------------------- ### Deserialize JSON data with a known root type Source: https://ts2python.readthedocs.io/en/latest/index.html Deserialize a JSON string into a Python object using the `json.loads` function. Ensure the root type of the JSON data is known beforehand. ```python import json request_msg: RequestMessage = json.loads(input_data) ``` -------------------------------- ### TypeScript Record Type to Python Dict Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt TypeScript Records are mapped to parameterized dictionaries in Python. ```typescript export interface Test { t: Record } ``` -------------------------------- ### Runtime Type Validation using Decorator Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html Apply the `type_check` decorator to your Python functions to automatically validate input parameters and return values against their type annotations at runtime. This is useful for catching type errors in dynamic scenarios. ```python from ts2python.json_validation import type_check @type_check def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### Direct Runtime Validation with validate_type Source: https://ts2python.readthedocs.io/en/latest/_sources/Validation.rst.txt Use the `validate_type` function for explicit runtime validation of a value against a specified TypedDict type. This function raises a `TypeError` if the validation fails, providing details about the error. ```python from ts2python.json_validation import validate_type, TypedDict 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) ``` -------------------------------- ### Handling Required and Optional Fields with @type_check Source: https://ts2python.readthedocs.io/en/latest/_sources/Validation.rst.txt Demonstrates how the `@type_check` decorator enforces required fields and rejects unexpected fields in TypedDicts, using `NotRequired` for optional fields. Ensure your TypedDicts inherit from `ts2python.json_validation.TypedDict`. ```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) ``` -------------------------------- ### Generated Python TypedDict Classes Source: https://ts2python.readthedocs.io/en/latest/BasicUsage.html The Python TypedDict classes generated from the provided TypeScript interfaces. These classes mirror the structure and types, enabling Python's static type checking. ```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'] ``` -------------------------------- ### Anonymous TypeScript Interface to Python TypedDict Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Anonymous interfaces in TypeScript are converted to local Python TypedDict classes. ```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; } ``` -------------------------------- ### Decorate Function for Runtime Type Checking Source: https://ts2python.readthedocs.io/en/latest/Validation.html Use the @type_check decorator to validate function parameters and return values against their type annotations at runtime. Parameters or return types without annotations are ignored. This is useful for ensuring data integrity in functions processing structured data like TypedDicts. ```python class Position(TypedDict, total=True): line: int character: int class Range(TypedDict, total=True): start: Position end: Position # just a fix for doctest stumbling over ForwardRef: Range.__annotations__ = {'start': Position, 'end': Position} @type_check def middle_line(rng: Range) -> Position: line = (rng['start']['line'] + rng['end']['line']) // 2 character = 0 return Position(line=line, character=character) rng = {'start': {'line': 1, 'character': 1}, 'end': {'line': 8, 'character': 17}} middle_line(rng) malformed_rng = {'start': 1, 'end': 8} try: middle_line(malformed_rng) except TypeError as e: print(e) ``` -------------------------------- ### Validate Value Against Type Source: https://ts2python.readthedocs.io/en/latest/Validation.html Use the validate_type function to raise a TypeError if a value is not of the specified type. This function is particularly useful for validating dictionaries against TypedDict types and general JSON data. ```python validate_type(1, int) validate_type(['alpha', 'beta', 'gamma'], List[str]) class Position(TypedDict, total=True): line: int character: int import json json_data = json.loads('{"line": 1, "character": 1}') validate_type(json_data, Position) bad_json_data = json.loads('{"line": 1, "character": "A"}') try: validate_type(bad_json_data, Position) except TypeError as e: print(e) ``` -------------------------------- ### TypeScript Enum to Python Enum Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Direct transpilation of a TypeScript enumeration with string values to a Python Enum. ```typescript export enum FoldingRangeKind { Comment = 'comment', Imports = 'imports', Region = 'region' } ``` ```python class FoldingRangeKind(Enum): Comment = 'comment' Imports = 'imports' Region = 'region' ``` -------------------------------- ### type_check decorator Source: https://ts2python.readthedocs.io/en/latest/Validation.html A decorator that validates the type of function parameters and the return value against their type annotations during runtime. Parameters or return types without annotations are ignored. It raises TypeErrors if mismatches occur. ```APIDOC ## Decorator: type_check ### Description Validates the type of parameters and the return value of a function against its type annotations during runtime. Parameters and return types without type annotations are silently ignored. ### Parameters * **func** (Callable) - The function to be decorated. Its parameters and return value will be type-checked. ### Returns * Callable - The decorated function which raises TypeErrors if parameter or return types do not match annotations. ``` -------------------------------- ### Deserialize JSON with TypeScript Interface Source: https://ts2python.readthedocs.io/en/latest/_sources/index.rst.txt Deserialize a JSON string into a Python TypedDict object when the root type is known. This assumes the JSON was generated from a TypeScript script. ```python import json request_msg: RequestMessage = json.loads(input_data) ``` -------------------------------- ### Runtime Type Validation with validate_type Source: https://ts2python.readthedocs.io/en/latest/_sources/BasicUsage.rst.txt Use the `validate_type` function from `ts2python.json_validation` to perform runtime type checking on de-serialized JSON data against a specified TypedDict. ```python import json from ts2python.json_validation import validate_type request_msg: RequestMessage = json.loads(input_data) validate_type(request_msg, RequestMessage) ``` -------------------------------- ### TypeScript Type Alias to Annotated Type Assignment (Python 3.10+) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html For Python 3.10 and above, type assignments are annotated with the TypeAlias type, supporting PEPs 586, 604, and 613. ```typescript type ProviderResult = T | undefined | null | Thenable; ``` ```python T = TypeVar('T') ProviderResult: TypeAlias = T | None | Coroutine[T | None] ``` -------------------------------- ### Runtime Type Validation with type_check Decorator Source: https://ts2python.readthedocs.io/en/latest/_sources/BasicUsage.rst.txt Apply the `type_check` decorator from `ts2python.json_validation` to a function to automatically validate its input parameters and return values against their annotated types at runtime. ```python from ts2python.json_validation import type_check @type_check def process_request(request: RequestMessage) -> ResponseMessage: ... return ResponseMessage(id = request.id) ``` -------------------------------- ### Nested Anonymous TypeScript Interface to Python TypedDict Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Nested anonymous interfaces in TypeScript are also converted to nested local Python TypedDict classes. ```typescript interface SemanticTokensClientCapabilities { dynamicRegistration?: boolean; requests: { range?: boolean | { }; full?: boolean | { delta?: boolean; }; }; tokenTypes: string[]; tokenModifiers: string[]; formats: TokenFormat[]; overlappingTokenSupport?: boolean; multilineTokenSupport?: boolean; } ``` -------------------------------- ### TypeScript Tuple Type to Python Tuple Type Source: https://ts2python.readthedocs.io/en/latest/Mapping.html Converts TypeScript tuple types to Python tuple types. Note the use of `Union` for fields that can be one of several 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']] ``` -------------------------------- ### Validating Types with `validate_type` Function Source: https://ts2python.readthedocs.io/en/latest/Validation.html Use the `validate_type` function to manually check if a given value conforms to a specified TypedDict. This function raises a TypeError if validation fails. Ensure the TypedDict class inherits from `ts2python.json_validation.TypedDict`. ```python from ts2python.json_validation import validate_type # Assuming Position TypedDict is defined as in the previous example # class Position(TypedDict, total=True): # line: int # character: int # Example of successful validation (no output) # validate_type({'line': 42, 'character': 11}, Position) try: validate_type({'line': 42, 'character': "bad mistake"}, Position) except TypeError as e: print(e) ``` -------------------------------- ### TypeScript Type Alias to Python Type Assignment (Python 3.7) Source: https://ts2python.readthedocs.io/en/latest/Mapping.html TypeScript type aliases are mapped to plain type assignments in Python when using the default compatibility level down to Python 3.7. ```typescript type ProviderResult = T | undefined | null | Thenable; ``` ```python T = TypeVar('T') ProviderResult = Union[T, None, Coroutine[Union[T, None]]] ``` -------------------------------- ### Runtime Validation with @type_check Decorator Source: https://ts2python.readthedocs.io/en/latest/_sources/Validation.rst.txt Use the `@type_check` decorator to automatically validate function arguments and return values against TypedDict type annotations. Ensure that your TypedDict classes inherit from `ts2python.json_validation.TypedDict` for runtime validation to work correctly. ```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) ``` -------------------------------- ### TypeScript Tuple Types to Python Tuple Types Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt TypeScript tuple types within interfaces are transpiled to Python Union types with Tuple. ```typescript export interface ParameterInformation { label: string | [uinteger, uinteger]; documentation?: string | MarkupContent; } ``` -------------------------------- ### TypeScript Literal Type to Python Literal Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt Conversion of a TypeScript literal union type to a Python Literal type. For Python versions below 3.8, the 'typing_extensions' module is required. ```typescript export type ResourceOperationKind = 'create' | 'rename' | 'delete'; ``` ```python ResourceOperationKind = Literal['create', 'rename', 'delete'] ``` -------------------------------- ### validate_type function Source: https://ts2python.readthedocs.io/en/latest/Validation.html Raises a TypeError if a given value is not of the specified type. This function is particularly useful for validating dictionaries against TypedDict types and JSON data in general. ```APIDOC ## Function: validate_type ### Description Raises a TypeError if the provided value `_val` is not of the specified type `_typ`. Useful for validating JSON data and dictionaries against TypedDict types. ### Parameters * **_val** (Any) - The value to be validated. * **_typ** (Type) - The expected type. ``` -------------------------------- ### TypeScript Enum without Quotes to Python IntEnum Source: https://ts2python.readthedocs.io/en/latest/_sources/Mapping.rst.txt TypeScript enums without quoted string members also convert to Python IntEnums. ```typescript enum MilkyWay { earth, moon, stars } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.