codemirr
TutorialsMirror CoursesReferencePlaygroundExamplesBlog
Pricing
Tutorials

TypeScript Generics vs Python Generic Types

Heaven

TypeScript Engineer

March 5, 2025
8 min read
typescriptpythongenericstypes

Generics let you write reusable code that works with multiple types while keeping type safety. Both TypeScript and Python support them — but their syntax looks quite different.

Basic Generic Function

**TypeScript:**

function identity<T>(value: T): T {
  return value;
}

const result = identity<string>("hello"); // string

**Python:**

from typing import TypeVar

T = TypeVar("T")

def identity(value: T) -> T:
    return value

result = identity("hello")  # str inferred by mypy

Generic Classes

**TypeScript:**

class Stack<T> {
  private items: T[] = [];
  push(item: T) { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
}

const stack = new Stack<number>();
stack.push(1);

**Python:**

from typing import Generic, TypeVar

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self.items: list[T] = []
    def push(self, item: T) -> None:
        self.items.append(item)
    def pop(self) -> T | None:
        return self.items.pop() if self.items else None

stack: Stack[int] = Stack()
stack.push(1)

Constraints

**TypeScript:**

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

**Python:**

from typing import Sized

def get_length(value: Sized) -> int:
    return len(value)

Key Differences

| Feature | TypeScript | Python |

|---|---|---|

| Generic syntax | `<T>` | `TypeVar("T")` |

| Generic class | `class Foo<T>` | `class Foo(Generic[T])` |

| Constraints | `T extends Base` | `TypeVar("T", bound=Base)` |

| Enforcement | Compile time | mypy / pyright (opt-in) |

Python 3.12+ Improvement

Python 3.12 introduced `type` statement and simplified generic syntax:

def identity[T](value: T) -> T:
    return value

This is much closer to TypeScript syntax.

Thanks for reading! Have questions?

codemirr

Learn to code with structured tutorials and innovative mirror courses.

DiscordGitHub

Product

  • Tutorials
  • Mirror Courses
  • Reference
  • Examples

Resources

  • Blog
  • Playground
  • Discord

Company

  • About
  • Contact
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service

© 2026 codemirr. All rights reserved.