How to use generics in TypeScript

· Category: TypeScript

Short answer

Generics let you write functions, interfaces, and classes that work with any type while preserving type information through type parameters.

Steps

  1. Define a generic function: function identity<T>(arg: T): T { return arg; }
  2. Use multiple parameters: function pair<T, U>(a: T, b: U): [T, U] { return [a, b]; }
  3. Constrain generics: function logLength<T extends { length: number }>(arg: T) { ... }
  4. Apply generics to interfaces: interface Response<T> { data: T; status: number; }
  5. Provide explicit type arguments when inference fails: identity<string>('hello');

Tips

  • Use descriptive names like TItem or TKey in complex signatures for clarity.
  • Default generic parameters simplify common use cases: interface Pagination<T = any>.

Common issues

  • Overly broad constraints like extends object often do not provide enough information for the function body.
  • Recursive generic types can produce confusing error messages when inference loops.