What if you could write one function that magically works for any list you have?
Why Generic functions with arrays in Typescript? - Purpose & Use Cases
Imagine you have several lists of different things: numbers, names, or even dates. You want to write a function that works on all these lists, but you write a new function for each type manually.
This means you write a lot of repeated code, which takes time and can easily have mistakes. If you want to change how the function works, you must update every version separately, which is tiring and error-prone.
Generic functions let you write one function that works with any type of array. You write the logic once, and it automatically adapts to numbers, strings, or any other type, saving time and avoiding mistakes.
function firstNumber(arr: number[]): number { return arr[0]; }
function firstString(arr: string[]): string { return arr[0]; }function firstElement<T>(arr: T[]): T { return arr[0]; }It enables writing flexible, reusable code that works with any kind of array without rewriting the same logic again and again.
Think about a shopping app that handles lists of products, prices, or user reviews. With generic functions, one function can process all these lists safely and easily.
Manual functions for each type cause repeated code and mistakes.
Generic functions work with any array type using one definition.
This saves time, reduces errors, and makes code reusable.