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
}In the above syntax:
- functionName : The name of the generic function.
- <T> : A type parameter, allowing the function to work with multiple types.
- parameterName: T : The function parameter whose type depends on the type argument.
- ReturnType : The type returned by the function, based on the type argument.
Example 1: Generic Function with Single Type Parameter
A generic function with a single type parameter works with different data types while ensuring type safety.
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
falseIn this example:
- The function
gfgtakes a generic parameterT. - It returns the same type it receives, ensuring type consistency.
- The function works for
string,number, andbooleanwithout rewriting.
Example 2: Generic Function with Array Parameter
Generics can also be applied to arrays, allowing functions to safely work with collections of different element types.
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
GeeksIn this example:
- The function
arrayEltakes a generic arrayT[]. - It works for both number arrays and string arrays.
- TypeScript ensures that only valid array elements are passed.
Example 3: Generic Function with Multiple Type Parameters
Generic functions can also use multiple type parameters, enabling flexible operations with different data types.
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"]In this example:
- The function
mergeArraysuses two generic typesTandU. - It merges arrays of different types into one.
- The return type is a union
(T | U)[], allowing elements of both types.