Junior (0-2 years)TypeScript

What are generics in TypeScript?

Quick answer

Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

identity<T>(value: T): T returns the same type it received. Without T you would write any and lose that link. Constraints (T extends { id: string }) describe the minimum shape. Several parameters (K, V) model maps and API wrappers.

Common interview follow-ups: default parameters (T = string), keyof T for safe property access, and why Array<T> and T[] are the same. Prefer inference (wrap(user)) over forcing wrap<User>(user) at every call site.

function first<T>(items: T[]): T | undefined {
  return items[0];
}

first(["a", "b"]);          // string | undefined
first<number>([1, 2, 3]);   // number | undefined