0
0
Typescriptprogramming~5 mins

Generic functions with arrays in Typescript

Choose your learning style9 modes available
Introduction

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.

When you want to create a function that can handle arrays of numbers, strings, or any other type without rewriting it.
When you want to keep your code flexible and reusable for different data types.
When you want to ensure type safety while working with arrays of various types.
When you want to avoid code duplication for similar operations on different array types.
Syntax
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.

Examples
This function returns the first element of any array or undefined if the array is empty.
Typescript
function getFirstElement<T>(array: T[]): T | undefined {
  return array[0];
}
This function returns a new array with the elements in reverse order without changing the original array.
Typescript
function reverseArray<T>(array: T[]): T[] {
  return array.slice().reverse();
}
This function returns an empty array of any type.
Typescript
function emptyArray<T>(): T[] {
  return [];
}
Sample Program

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.

Typescript
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));
OutputSuccess
Important Notes

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.

Summary

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.