![]() |
VOOZH | about |
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:
A generic function with a single type parameter works with different data types while ensuring type safety.
Output:
GEEKSFORGEEKS
740
falseIn this example:
gfg takes a generic parameter T.string, number, and boolean without rewriting.Generics can also be applied to arrays, allowing functions to safely work with collections of different element types.
Output:
101
102
103
Geeks
For
GeeksIn this example:
arrayEl takes a generic array T[].Generic functions can also use multiple type parameters, enabling flexible operations with different data types.
Output:
[1, 2, 3, "hello", "world"]In this example:
mergeArrays uses two generic types T and U.(T | U)[], allowing elements of both types.