TypeScript Generics
Generics let you write reusable functions, classes, and types that work with a variety of types while still preserving type information. Instead of hardcoding one specific type, you use a placeholder like `T`.
When a generic function is called, TypeScript infers or you specify the actual type to use for `T`, and it enforces that type consistently everywhere the placeholder appears.
function identity<T>(value: T): T {
return value;
}Generic functions
You write a generic function using angle brackets, like `function identity<T>(value: T): T { return value; }`. TypeScript infers T from the argument you pass in.
Generic constraints
You can restrict what types are allowed for a generic parameter using `extends`, ensuring the placeholder type has certain required properties.
function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(5));
console.log(identity("hello"));5
helloT adapts to whatever type is passed in, while still preserving type safety.
function firstElement<T>(arr: T[]): T {
return arr[0];
}
console.log(firstElement([1, 2, 3]));
console.log(firstElement(["a", "b"]));1
aThe generic function works with arrays of any type and returns the correct element type.
Key points
- Generics use a placeholder type, commonly named T, in angle brackets.
- TypeScript can infer the generic type from arguments automatically.
- Generics keep code reusable without losing type safety.
- Generic constraints use `extends` to require certain properties.
