VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-generic-functions/

⇱ TypeScript Generic Functions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript Generic Functions

Last Updated : 15 Sep, 2025

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.

Output:

GEEKSFORGEEKS
740
false

In this example:

  • The function gfg takes a generic parameter T.
  • It returns the same type it receives, ensuring type consistency.
  • The function works for string, number, and boolean without 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.

Output:

101
102
103
Geeks
For
Geeks

In this example:

  • The function arrayEl takes a generic array T[].
  • 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.

Output:

[1, 2, 3, "hello", "world"]

In this example:

  • The function mergeArrays uses two generic types T and U.
  • It merges arrays of different types into one.
  • The return type is a union (T | U)[], allowing elements of both types.
Comment
Article Tags:

Explore