How to use generics in TypeScript
· Category: TypeScript
Short answer
Generics let you write functions, interfaces, and classes that work with any type while preserving type information through type parameters.
Steps
- Define a generic function:
function identity<T>(arg: T): T { return arg; } - Use multiple parameters:
function pair<T, U>(a: T, b: U): [T, U] { return [a, b]; } - Constrain generics:
function logLength<T extends { length: number }>(arg: T) { ... } - Apply generics to interfaces:
interface Response<T> { data: T; status: number; } - Provide explicit type arguments when inference fails:
identity<string>('hello');
Tips
- Use descriptive names like
TItemorTKeyin complex signatures for clarity. - Default generic parameters simplify common use cases:
interface Pagination<T = any>.
Common issues
- Overly broad constraints like
extends objectoften do not provide enough information for the function body. - Recursive generic types can produce confusing error messages when inference loops.