Dmytro Morar
TypeScript

Generics

Generics add type parameters to functions, classes, or interfaces for reusable, type-safe code.

Example

function identity<T>(value: T): T {
  return value;
}
const num = identity<number>(10);
const str = identity("Hello");

Data structures

interface Box<T> {
  content: T;
}
const stringBox: Box<string> = { content: "TypeScript" };

Constraints

function getLength<T extends { length: number }>(item: T): number {
  return item.length;
}

On this page