Generics#
A generic is a type parameter. <T> declares the slot; the
caller (or inference) fills it.
Generic function.
function head<T>(xs: T[]): T | undefined {
return xs[0];
}
Inference at the call site.
const n = head([1, 2, 3]); // n: number | undefined
const s = head(["a", "b"]); // s: string | undefined
Generic class.
class Container<T> {
constructor(public value: T) {}
}
Constraints narrow what T can be.
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
The constraint catches a bad key at compile time.
pluck({name: "rk", age: 30}, "name"); // string
pluck({name: "rk", age: 30}, "age"); // number
pluck({name: "rk", age: 30}, "xyz"); // Error: not a key
References#
Type operators for
keyof T(used as a constraint above).Conditional and mapped for conditional generic structures.