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)

TypeScriptPython (Type Hints / Typing)Notes
interface Position { x: number; y: number }class Position(TypedDict): x: int; y: intTypedDict 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
anyAny (from typing)Try to avoid both 😅
unknownobject or Any + manual type checksPython has no direct equivalent
Optional props: foo?: number`foo: intNone = None`
function greet(name: string): stringdef greet(name: str) -> str:Just plain old function annotations
abstract classclass Thing(ABC): @abstractmethod def run()Or manual raise NotImplementedError
class Animal { constructor(public x: number) }class Animal: def __init__(s, x: int): s.x = xPython makes props in __init__
implements InterfaceNo strict equivalent — just duck typingPython checks at runtime only
Generics: <T>Generic[T] from typingYou can do it, just less common in casual use
as type assertion: val as stringcast(str, val)From typing, for enforced casts
readonly x: numberNo 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 _name for 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’s undefined or null depending on context.

#python #typescript #python2typescript #typescript2python