Zet - What are some comparison to types in python compared to typescript?
What are some comparison to types in python compared to typescript?
🧠 TypeScript ↔ Python Cheat Sheet (for Devs Who Think in TypeScript)
| TypeScript | Python (Type Hints / Typing) | Notes |
|---|---|---|
interface Position { x: number; y: number } | class Position(TypedDict): x: int; y: int | TypedDict gives structure to dicts |
type Direction = "left" | "right" | Direction = Literal["left", "right"] | Literal is the TS union of constants |
Record<string, number> | dict[str, int] | Basic dict typing |
any | Any (from typing) | Try to avoid both 😅 |
unknown | object or Any + manual type checks | Python has no direct equivalent |
Optional props: foo?: number | `foo: int | None = None` |
function greet(name: string): string | def greet(name: str) -> str: | Just plain old function annotations |
abstract class | class Thing(ABC): @abstractmethod def run() | Or manual raise NotImplementedError |
class Animal { constructor(public x: number) } | class Animal: def __init__(s, x: int): s.x = x | Python makes props in __init__ |
implements Interface | No strict equivalent — just duck typing | Python checks at runtime only |
Generics: <T> | Generic[T] from typing | You can do it, just less common in casual use |
as type assertion: val as string | cast(str, val) | From typing, for enforced casts |
readonly x: number | No built-in, but convention is _x (private-ish) | True immutability needs a frozen dataclass |
Enums: enum Direction { Left, Right } | from enum import Enum (or just use Literals) | Literals are simpler if all you need is constants |
Type narrowing: typeof x === "string" | isinstance(x, str) | Python’s way to narrow types |
✅ Example: Typed Config Objects
TypeScript:
interface EnemyArgs {
x: number;
y: number;
direction: "left" | "right";
}
const enemy = new Enemy({ x: 0, y: 0, direction: "left" });
Python:
from typing import TypedDict, Literal
Direction = Literal["left", "right"]
class EnemyArgs(TypedDict):
x: int
y: int
direction: Direction
enemy = Enemy({"x": 0, "y": 0, "direction": "left"})
🚨 Differences to Watch Out For
- Everything is public in Python. Use
_namefor private-ish convention. - Type hints aren’t enforced at runtime unless you add checks.
- Python functions default to positional args, but you can force keyword-only args with
*. - Python’s
None= TypeScript’sundefinedornulldepending on context.
#python #typescript #python2typescript #typescript2python