Generic class

2 snippets across 2 stacks — Python, TypeScript

PYPython

Type Parameter Syntax (3.12+)

PY · Modern Features
syntax
def func[T](arg: T) -> T: ...
class Name[T]: ...
example
# New syntax (3.12+) - no more TypeVar boilerplate
def first_element[T](items: list[T]) -> T:
    return items[0]

print(first_element([10, 20, 30]))
print(first_element(["a", "b"]))

# Generic class
class Pair[A, B]:
    def __init__(self, left: A, right: B):
        self.left = left
        self.right = right

p = Pair("name", 42)
print(p.left, p.right)
output
10
a
name 42

Note The [T] syntax on def/class replaces manual TypeVar declarations. It is scoped to the function or class, unlike module-level TypeVar which could be reused accidentally.

TSTypeScript

Generic Classes

TS · Generics
syntax
class Name<T> {
  constructor(private value: T) {}
}
example
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }

  get size(): number {
    return this.items.length;
  }
}

const numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
const top = numberStack.pop(); // number | undefined
output
// top → 20

Note Static members of a generic class cannot reference the class type parameter — the parameter only exists on instances. If you need generic static methods, make the method itself generic rather than the class.