Generic Constraints

Restrict a type parameter so it must have certain properties.

Syntaxfunction len<T extends { length: number }>(x: T)

Use extends to constrain a type parameter, requiring it to have specific members. This lets you safely use those members inside the function.

Example

<T extends { length: number }> accepts anything with a length property, such as strings and arrays.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A merge function constrains T and U to object so it safely spreads them without accepting primitives.
  • A getLength function constrains T to { length: number } so it works on both strings and arrays.
  • A lookup function constrains K to keyof T so only valid property names can be passed as the key argument.

More examples

Constrain to length property

Constrains T to any type that has a length property, making the function work for strings and arrays but not numbers.

Example Β· ts
function logLength<T extends { length: number }>(value: T): void {
  console.log('Length:', value.length);
}

logLength('hello');       // string has .length
logLength([1, 2, 3]);     // array has .length
logLength(42);            // Error: number has no .length

keyof constraint

Constrains K to be a key of T so the compiler can both validate the key and infer the correct value type.

Example Β· ts
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 1, name: 'Alice' };
const name = getProperty(user, 'name'); // string
const id   = getProperty(user, 'id');   // number
// getProperty(user, 'email');          // Error: not a key of user

Extends object constraint

Constrains both type parameters to object so the spread merge rejects primitive arguments at compile time.

Example Β· ts
function merge<T extends object, U extends object>(a: T, b: U): T & U {
  return { ...a, ...b };
}

const result = merge({ x: 1 }, { y: 'hello' });
// result: { x: number } & { y: string }

Discussion

  • Be the first to comment on this lesson.
Generic Constraints β€” TypeScript | SoundsCode