Script Valley
TypeScript: Complete Course from Zero
GenericsLesson 4.2

Generic constraints in TypeScript using extends

extends constraint, constraining to interface, keyof constraint, multiple constraints, why unconstrained generics fail

Why constraints are needed

An unconstrained T cannot access any properties โ€” TypeScript does not know what T looks like:

function getName(obj: T): string {
  return obj.name; // Error: Property 'name' does not exist on type 'T'
}

Add a constraint with extends:

function getName(obj: T): string {
  return obj.name; // safe
}

getName({ name: "Alice", age: 30 }); // works
getName({ id: 1 });                  // Error: missing name

keyof constraint

function getProperty(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: "Alice", age: 30 };
getProperty(user, "name");  // string
getProperty(user, "age");   // number
getProperty(user, "email"); // Error: not a key of user

The keyof T produces a union of all keys of T as string literals. T[K] is an indexed access type โ€” the type of the value at key K. Together they make getProperty fully type-safe.

Up next

Generic interfaces and generic classes in TypeScript

Sign in to track progress

Generic constraints in TypeScript using extends โ€” Generics โ€” TypeScript: Complete Course from Zero โ€” Script Valley โ€” Script Valley