Generics
Write once, use for any type — generic functions, interfaces, and constraints
Skills taught: ts.generic-functions, ts.generic-interfaces, ts.generic-constraints, ts.generic-classes
Generic functions
// Without generics — you'd need a separate function per type:
// function wrapString(x: string): string[] { return [x]; }
// function wrapNumber(x: number): number[] { return [x]; }
// With generics — one function for ALL types:
function wrap<T>(item: T): T[] {
return [item];
}
console.log(wrap('hello')); // ['hello'] — TypeScript infers T as string
console.log(wrap(42)); // [42] — T inferred as number
console.log(wrap(true)); // [true] — T inferred as boolean
// The return type is T[], not any[] — still type-safe!
const strings = wrap('world'); // string[]
const nums = wrap(99); // number[]
// Generic identity function
function identity<T>(arg: T): T {
return arg;
}
// Multiple type params
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
console.log(pair('Alice', 30)); // ['Alice', 30] (type: [string, number])
console.log(pair(1, true)); // [1, true] (type: [number, boolean])
// Generic with array utilities
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
function last<T>(arr: T[]): T | undefined {
return arr[arr.length - 1];
}
console.log(first([10, 20, 30])); // 10
console.log(last(['a', 'b', 'c'])); // 'c'
Constraints and generic interfaces
// Constraint: T extends string — T must have a length property
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest('hello', 'hi')); // 'hello'
console.log(longest([1, 2, 3], [4, 5])); // [1, 2, 3]
// keyof constraint — K must be a key of T
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Alice', age: 30, role: 'admin' };
console.log(getProperty(user, 'name')); // 'Alice' (string)
console.log(getProperty(user, 'age')); // 30 (number)
// getProperty(user, 'xyz'); // Error: 'xyz' is not a key of user
// Generic interface
interface Box<T> {
value: T;
map<U>(fn: (val: T) => U): Box<U>;
}
// Generic class — typed data structure
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 numStack = new Stack<number>();
numStack.push(1);
numStack.push(2);
numStack.push(3);
console.log(numStack.peek()); // 3
console.log(numStack.pop()); // 3
console.log(numStack.size); // 2
Frequently Asked Questions
When should I add a constraint (T extends Something) vs leave T unconstrained?
Add a constraint when you need to use a property or method of T inside the function body. If you just store or return T (identity, wrap, pair), leave it unconstrained. If you call T.length or T.toString(), constrain with T extends { length: number } etc. The constraint expresses what you actually need, and TypeScript enforces it at call sites.