Push Type Parameters Down
It’s frequently preferable to define type parameters at the top level rather than at the level of individual function signatures when developing generic functions with many type parameters. This improves adaptability and enables more accurate type inference.
Dont’s:
function findMax<T extends number>(numbers: T[]): T | undefined {
if (numbers.length === 0) {
return undefined;
}
return Math.max(...numbers);
}
Do’s:
function mergeArrays<T, U>(arr1: T[], arr2: U[]): (T | U)[] {
return [...arr1, ...arr2];
}
TypeScript Guidelines for Writing Good Generic Functions
Generics in TypeScript allow you to write reusable and flexible functions and classes by introducing type parameters. They enable you to create functions that work with different data types while maintaining type safety. However, writing good generic functions requires careful consideration of types, constraints, and usage patterns.
These are the following methods that need to be fulfilled while creating a generic function:
Table of Content
- Push Type Parameters Down
- Use Fewer type parameters
- Type Parameters Should Appear Twice