Skip to main content

Generics & Templates

Generics allow you to write type-safe, reusable code. Here's how different languages handle generic programming.

Basic Generics​

// JavaScript has no built-in generics
// Use TypeScript for generic support

// TypeScript generics:
// function identity<T>(value: T): T {
// return value;
// }
// identity<string>("hello");
// identity<number>(42);

// Generic interface (TypeScript)
// interface Container<T> {
// value: T;
// getValue(): T;
// }

// Generic class (TypeScript)
// class Box<T> {
// constructor(private value: T) {}
// get(): T { return this.value; }
// }
// const box = new Box<string>("hello");

Type Constraints​

// TypeScript constraints
// function max<T extends number>(a: T, b: T): T {
// return a > b ? a : b;
// }

// Interface constraint
// interface HasLength { length: number; }
// function logLength<T extends HasLength>(item: T): void {
// console.log(item.length);
// }
// logLength("hello"); // OK
// logLength([1, 2, 3]); // OK
// logLength(42); // Error

// keyof constraint
// function getProperty<T, K extends keyof T>(
// obj: T, key: K
// ): T[K] {
// return obj[key];
// }

Key Takeaways​

  • Type erasure vs monomorphization -- Java and TypeScript erase generics at runtime (one shared representation); C++, Rust, Swift, and Go generate specialized code per type (monomorphization) for zero-cost abstraction.
  • Constraint systems vary in expressiveness -- Rust's traits and C++ concepts offer rich bounds; Go's type sets (~int | ~float64) and Swift's protocol constraints are simpler; Java's extends and wildcards are more limited.
  • Languages without generics use workarounds -- C uses void* and macros; JavaScript/Ruby rely on duck typing; PHP uses docblock annotations for static analysis; Zig uses comptime type parameters.
  • Comptime generics (Zig) are unique -- Zig passes types as compile-time values, enabling zero-cost generics without a separate type parameter syntax; types are first-class at compile time.
  • Python and PHP have late generics -- Python 3.12+ and PHPStan/Psalm add generic syntax; type checking is static only—runtime behavior is unchanged—unlike compiled languages.