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.

Frequently asked questions

How does Python handle generic class?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Type Parameter Syntax (3.12+)" snippet in Python uses `def func[T](arg: T) -> T: ...`.
Which code does the Python example use?
The "Type Parameter Syntax (3.12+)" snippet uses `def func[T](arg: T) -> T: ...`, from the Modern Features section of the Python cheat sheet.
Which stacks cover "generic class" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Parameter Syntax (3.12+)": 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.