Browse topics

TypeScript generics

Version
es2025
Since
0.9
Review
Draft

Summary#

A generic declares type parameters that connect the types of inputs and outputs. A constraint written with extends limits the accepted types and states what the code may rely on.

Syntax#

ts
function name<Item extends Constraint>(value: Item): Item {
  return value;
}

Example#

ts
function pluck<Item, Key extends keyof Item>(
  items: Item[],
  key: Key
): Item[Key][] {
  return items.map((item) => item[key]);
}

const books = [
  { title: "Atlas", pages: 120 },
  { title: "Field notes", pages: 80 },
];

const pages: number[] = pluck(books, "pages");
console.log(pages.join(","));
console.log(pluck(books, "title").join(" | "));

Expected output#

Text
120,80
Atlas | Field notes

Common mistakes#

A type parameter that appears only in the return type, as in parse<Result>(text: string): Result, lets the caller claim any type without a check. Return unknown and validate it. Type arguments are erased, so runtime code cannot inspect them.

Version applicability#

TypeScript 0.9 added generics. The complete example needs TypeScript 2.1 for keyof and the indexed access type Item[Key]. Compile or strip the type syntax before running it in a JavaScript-only runtime.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0