Open In App

TypeScript Guidelines for Writing Good Generic Functions

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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];
}

Use Fewer type parameters

Try to use as few type parameters as possible in your generic functions. Your code will be easier to read and comprehend if there are fewer type parameters.

Dont’s:

function findMax<T, U, V>(numbers: T[], flags: U[], labels: V[]): T | undefined {
// Function body...
}

Do’s:

function findMax<T extends number>(numbers: T[]): T | undefined {
if (numbers.length === 0) {
return undefined;
}
return Math.max(...numbers);
}

Type Parameters Should Appear Twice

Make sure that each type parameter appears at least twice in your function signature when working with multiple type arguments. This encourages the type parameters to be used in meaningful ways.

Dont’s:

function mergeObjects<T, U>(obj1: T, obj2: U): (T & U) {
return { ...obj1, ...obj2 };
}

Do’s:

function mergeObjects<T, K extends keyof T>(obj1: T, obj2: T): T {
return { ...obj1, ...obj2 };
}

Example: Showing Push Type Parameters Down

Javascript




function mergeArrays<T, U>
    (arr1: T[], arr2: U[]): (T | U)[] {
    return [...arr1, ...arr2];
}
const numbers = [1, 2, 3];
const strings = ["apple", "banana"];
const mergedArray = mergeArrays(numbers, strings);
console.log(`Merged array: ${mergedArray}`);


Output:

Merged array: 1,2,3,apple,banana

Conclusion: In this article, We have seen the guidlines for writing good generic functions. By following these guidelines for generic functions with multiple type parameters, you can write more readable and maintainable TypeScript code. Push type parameters down, use fewer type parameters when possible, and ensure that each type parameter appears at least twice in your function signatures.

Reference: https://www.typescriptlang.org/docs/handbook/2/functions.html#guidelines-for-writing-good-generic-functions


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads