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.
TypeScript Generic Functions - FAQs
What is type inference in generic functions?
Type inference allows TypeScript to automatically determine the type parameter of a generic function based on the arguments passed, simplifying function calls without needing explicit type specification.
What are constraints in TypeScript Generic Functions?
Constraints limit the types that can be used as arguments in a generic function by using the extends keyword. For example, <T extends number> restricts T to number types.
How do Generic Functions handle type inference in TypeScript?
TypeScript's type inference automatically determines the type parameter based on the arguments passed to the function, reducing the need to explicitly specify types when calling the function.
Are there any performance implications of using Generic Functions in TypeScript?
There are no runtime performance impacts because generics are a compile-time feature. TypeScript removes generics during compilation, so they only provide type safety and flexibility during development.
What is the difference between Generic Functions and Overloads in TypeScript?
Generic functions provide a single implementation that adapts to multiple types, while overloads define multiple specific signatures for different types, which can be more verbose and less flexible.