Generic functions let you write one function that works with many types of data. This saves time and avoids repeating code for different data types.
Generic functions with arrays in Typescript
function functionName<T>(array: T[]): T[] { // function body return array; }
The <T> is a placeholder for any type you want to use.
You use T[] to say the function works with an array of type T.
undefined if the array is empty.function getFirstElement<T>(array: T[]): T | undefined { return array[0]; }
function reverseArray<T>(array: T[]): T[] { return array.slice().reverse(); }
function emptyArray<T>(): T[] { return []; }
This program defines a generic function to get the first element of any array. It tests the function with a number array, a string array, and an empty array.
function getFirstElement<T>(array: T[]): T | undefined { return array[0]; } const numberArray = [10, 20, 30]; const stringArray = ['apple', 'banana', 'cherry']; const emptyArray: number[] = []; console.log('First number:', getFirstElement(numberArray)); console.log('First string:', getFirstElement(stringArray)); console.log('First element of empty array:', getFirstElement(emptyArray));
Time complexity is O(1) because it just accesses the first element.
Space complexity is O(1) since it does not create new data.
A common mistake is forgetting to handle empty arrays, which can cause undefined results.
Use generic functions when you want one function to work with many types safely instead of writing many similar functions.
Generic functions use <T> to work with any data type.
They help avoid repeating code for different array types.
Always consider empty arrays when working with generic array functions.