Generics

Parameterize types and functions over types for reusable, type-safe code.

Since TS 1.0 Spec ↗

Syntax

function fn<T>(arg: T): T

Examples

function identity<T>(value: T): T {
  return value;
}
const n = identity(42); // T inferred as number
interface Box<T> { value: T }
function unwrap<T>(b: Box<T>): T { return b.value; }

Notes

Type parameters let a definition work over many types while preserving relationships between inputs and outputs. Constrain them with `extends`, provide defaults (`<T = string>`), and use `const` type parameters (TS 5.0) to infer literal types. Inference usually makes explicit type arguments unnecessary.

See also