Generics Basics
Why generics exist
Without generics you often fall back to any. A type parameter keeps input and output related.
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([10, 20]));
console.log(first(["a", "b"]));
Constrain a type parameter
extends limits T to types that have the required shape.
function labelOf<T extends { name: string }>(item: T): string {
return item.name;
}
console.log(labelOf({ name: "Course", id: 1 }));
Generic interfaces
Containers like boxes or API responses often take a type argument.
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const textBox: Box<string> = { value: "hi" };
Keep generics simple
- Start with one type parameter named
T - Add constraints only when you need specific properties
- Let inference work at call sites when possible
- Do not introduce generics when a concrete type is enough
Comments
One comment per signed-in account. Comments are saved with this page’s URL.