TypeScript Generic Functions
TypeScript generic functions allow you to create functions that work with various types while maintaining type safety. By using type parameters, defined within angle brackets (<T>), generics enable functions to operate on different data types without losing the benefits of TypeScript's type-checking.
Syntax:
function functionName<T>(parameterName: T): ReturnType {
// the implementation
}
Where-
- functionName is the name of your generic function.
- <T> is the type parameter, T, allowing you to work with different data types within the function.
- parameterName represents the name of the function's parameter, and T designates the type of data the parameter will accept.
- ReturnType specifies the expected type for the function's return value.
Example: A generic function with a single type parameter in TypeScript works with various data types while ensuring type safety. You specify or let TypeScript infer the type for arguments and return values.
function gfg<T>(arg: T): T {
return arg;
}
let result1: string = gfg<string>("GEEKSFORGEEKS");
let result2: number = gfg<number>(740);
let result3: boolean = gfg<boolean>(false);
console.log(result1);
console.log(result2);
console.log(result3);
Output:
GEEKSFORGEEKS
740
false
Example: A generic function with an array parameter allows you to work with arrays of different types. By using a type parameter, the function can handle arrays of various element types while maintaining type safety.
function arrayEl<T>(arr: T[]): void {
for (const x of arr) {
console.log(x);
}
}
let elements: number[] = [101, 102, 103];
arrayEl(elements);
let elements1: string[] = ["Geeks", "For", "Geeks"];
arrayEl(elements1);
Output:
101
102
103
Geeks
For
Geeks
Example: In this example the function mergeArrays merges two arrays of different types into one. It takes arrays of type T and U, and returns an array of type (T | U)[].
function mergeArrays<T, U>(arr1: T[], arr2: U[]): (T | U)[] {
return [...arr1, ...arr2];
}
// Arrays with different types
const numbers: number[] = [1, 2, 3];
const words: string[] = ["hello", "world"];
// Merging arrays of different types
const mergedArray: (number | string)[] = mergeArrays(numbers, words);
// Outputting the merged array
console.log(mergedArray);
Output:
[1, 2, 3, "hello", "world"]
Conclusion: In TypeScript, generic functions let you build versatile functions that work with different data types while ensuring your code stays error-free. This flexibility is incredibly handy when you want to create functions that can handle a variety of situations without repeating code. Whether you're working with arrays, objects, or any data structure, generic functions empower you to write cleaner and safer code.