On this page
  1. Generics, Constraints & Variance
  2. Contents
  3. Generic Constraints (extends & keyof)
  4. Variance (out Covariant vs. in Contravariant)

Generics, Constraints & Variance

Prev: Structural Typing & Narrowing | Up: type_system | Next: Conditional, Mapped & Template Literal Types
Rel: keyof, NoInfer
Ref: TypeScript Handbook โ€” Generics
Tags: #public #web #typescript #type-system #generics


Contents


Generic Constraints (extends & keyof)

Constrain generic type parameters with extends to guarantee required properties while preserving exact return types:

function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Grace" }];
const names = pluck(users, "name"); // string[]

Variance (out Covariant vs. in Contravariant)

Explicit in/out annotations on generic interfaces speed up type checking and document intent.

Linked from

Related notes