Skip to content

Syntax Reference

python2ts supports comprehensive Python syntax conversion to TypeScript.

Literals & Operators

PythonTypeScriptNotes
True / False / Nonetrue / false / null
x // yfloorDiv(x, y)Python semantics (rounds toward -inf)
x ** ypow(x, y)
x % ymod(x, y)Python semantics (follows divisor sign)
x in itemscontains(items, x)
arr[1:3] / arr[::-1]slice(...)Full slice support

Control Flow

PythonTypeScript
if/elif/elseif/else if/else
for x in items:for (const x of items)
for x, y in items:for (const [x, y] of items)
match x: / case _:switch / default:

Functions

PythonTypeScript
def fn(*args):function fn(...args)
def fn(**kwargs):function fn(kwargs)
lambda x: x + 1(x) => (x + 1)
async def / awaitasync function / await
yield / yield fromyield / yield*

Classes

PythonTypeScript
class Child(Parent):class Child extends Parent
def __init__(self):constructor()
self.xthis.x
super().__init__()super()
@dataclassAuto-generated constructor
@staticmethod / @classmethodstatic
@property / @x.setterget / set

Type Hints

PythonTypeScript
x: List[int]x: number[]
x: Dict[str, T]x: Record<string, T>
x: Optional[str]x: string | null
Callable[[int], str](arg0: number) => string
Generic[T]<T>
Protocolinterface
TypedDictinterface
Final[T]const / readonly
ClassVar[T]static
Literal["a", "b"]"a" | "b"

Comprehensions

# List comprehension
[x * 2 for x in items]
# -> items.map(x => x * 2)
# With filter
[x for x in items if x > 0]
# -> items.filter(x => x > 0)
# Dict comprehension
{k: v for k, v in pairs}
# -> Object.fromEntries(pairs.map(([k, v]) => [k, v]))
# Set comprehension
{x * 2 for x in items}
# -> new Set(items.map(x => x * 2))

Imports

PythonTypeScript
import osimport * as os from "os"
from os import pathimport { path } from "os"
from . import utilsimport * from "./utils"

Runtime module imports (itertools, functools, collections, etc.) are automatically handled by the runtime.

Exception Handling

try:
risky_operation()
except ValueError as e:
handle_error(e)
finally:
cleanup()

Becomes:

try {
risky_operation()
} catch (e) {
if (e instanceof Error) {
handle_error(e)
}
} finally {
cleanup()
}

Docstrings

Python docstrings (Google, NumPy, or simple styles) are converted to JSDoc:

def calculate(x: int, y: int) -> int:
"""Calculate the sum of two numbers.
Args:
x: First number
y: Second number
Returns:
The sum of x and y
"""
return x + y

Becomes:

/**
* Calculate the sum of two numbers.
*
* @param x - First number
* @param y - Second number
* @returns The sum of x and y
*/
function calculate(x: number, y: number): number {
return x + y
}