← Lessons

quiz vs the machine

Gold1380

Frontend

Generics in TypeScript

Write one reusable function or type that works across many concrete types.

5 min read · core · beat Gold to climb

The problem generics solve

You often want a function that works for any type while still relating its inputs and outputs. Without generics you would lose type information or copy the function for each type.

Type parameters

A generic introduces a type parameter, often named T, that stands in for a real type chosen at the call site. An identity function takes a T and returns a T, so passing a number returns a number, not a vague any.

Inference at the call site

You rarely write the type argument by hand. TypeScript infers T from the values you pass. Calling identity with a string sets T to string automatically.

Constraints

A generic can be limited with extends so it only accepts types meeting a shape. A function that reads a length can constrain T to types that have a length property, rejecting values that lack it.

Why it matters

  • One implementation serves many types with no loss of safety.
  • The relationship between input and output stays visible to the checker.
  • Containers like arrays, promises, and maps are generic for exactly this reason.

Key idea

Generics carry type information through a reusable function so one definition stays precise for every concrete type.

Check yourself

Answer to earn rating on the learn ladder.

1. How is the type parameter T usually determined?

2. What does extends do in a generic parameter?