Skip to main content
A generic function in TypeScript is a function parameterized over types. It declares one or more type variables (type parameters) enclosed in angle brackets (< >) immediately preceding the function’s parameter list. This mechanism allows the function to capture the specific types provided by the caller, establishing a strict, statically-analyzed relationship between the input parameters, internal logic, and the return type without sacrificing type safety or resorting to the any type.

Syntax Declarations

The placement of the type parameter varies slightly depending on how the function is declared.
Note: When writing generic arrow functions in .tsx files, the compiler can confuse the <T> syntax with a JSX element. To resolve this parser ambiguity, append a trailing comma to the type parameter: <T,>(payload: T) => payload;

Type Parameters vs. Type Arguments

  • Type Parameter: The placeholder variable declared in the function signature (e.g., the T in <T>).
  • Type Argument: The concrete type bound to the parameter during invocation (e.g., the string in process<string>("data")).

Type Inference

TypeScript’s compiler utilizes type argument inference to automatically determine the type argument based on the runtime arguments passed to the function. Explicitly passing the type argument is only required when the compiler lacks sufficient context to infer it correctly.

Multiple Type Parameters

Functions can declare multiple type parameters by separating them with commas. This is used to establish relationships between distinct types within the same function signature.

Generic Constraints

By default, an unconstrained type parameter can accept any type. To safely access specific properties or methods on a generic parameter, you must constrain it using the extends keyword. This enforces that the type argument satisfies a specific structural contract.

Type Parameter Defaults

Type parameters can be assigned default types. If the compiler cannot infer the type from the invocation context and no explicit type argument is provided, it will fall back to the default type.

Constraining Types by Other Type Parameters

A type parameter can be constrained by another type parameter declared in the same function signature. This is frequently used to enforce that a parameter is a valid key of another parameter’s type using the keyof operator.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More