TypeScript

Generic Constraints with `extends`

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generics start unbounded — you can't access any properties of `T`. `T extends { … }` adds a constraint so the body can safely use known shape, while callers can still pass in narrower types.
TypeScript
Raw
// Pick a property by key, preserving its exact type.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 42, name: 'Alice' };
const id   = getProp(user, 'id');     // number
const name = getProp(user, 'name');   // string
// getProp(user, 'zzz');               // ✗ "zzz" is not in keyof user

// Constraint to a shape:
function hasId<T extends { id: unknown }>(x: T): boolean {
  return x.id !== null && x.id !== undefined;
}

hasId({ id: 1, name: 'a' });   // ✓
hasId({ name: 'a' });          // ✗ missing `id`
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.