Skip to content

Lesson 2 of 9 · 24m

Constraints and Inference: Let the Compiler Do the Work

How extends narrows type parameters, why inference breaks at object boundaries, and the patterns that keep precise types without making call sites miserable.

Generics without constraints are too permissive to model real systems. Most values you care about are not "anything"; they are "anything with an id," "any key of this object," or "any constructor that produces a service." extends is how you say that without surrendering the exact type information you worked hard to preserve.

Constraints describe requirements, not exact types

function byId<T extends { id: string }>(items: readonly T[]) {
  return new Map(items.map((item) => [item.id, item]));
}

const invoiceRows = byId([
  { id: "inv_1042", customer: "Acme", total: 4900 },
]);

// Map<string, { id: string; customer: string; total: number }>

The constraint says every element must have an id, but inference still keeps the full row shape. That is the difference between a useful abstraction and a type-level blender.

keyof is the workhorse constraint

function pick<T, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K> {
  const out = {} as Pick<T, K>;
  for (const key of keys) out[key] = obj[key];
  return out;
}

const publicUser = pick(user, ["id", "displayName"] as const);

K extends keyof T means the keys cannot drift away from the object. Rename displayName to name and every stale picker fails at compile time instead of shipping undefined into a UI.

Inference has edges you will hit

TypeScript infers object literal properties as wider than you often want:

const config = { mode: "strict" };
// mode: string, not "strict"

Use as const when the literal matters:

const config = { mode: "strict" } as const;
// mode: "strict"

The reverse trap is over-constraining input. If a helper only reads length, don't demand readonly string[] unless ownership matters; accept what you need and no more.

Field notes

  • Error messages like "string is not assignable to never" often mean inference unioned an impossible branch or a key constraint collapsed.
  • Put as const on the array or object at the boundary where literal shape matters, not randomly throughout the file.
  • Constraints do not exist at runtime. TypeScript can prove shape; it cannot conjure runtime validation.
  • If inference is noisy in tests, write a tiny expectType<T>(value) helper and compile-test API ergonomics directly.

Was this lesson helpful?

Sign in to rate