Syncing account progress…

Back

Intermediate · 14 min

Generic constraints

Require the properties a generic function uses while preserving its input type.

State the minimum requirement

A generic type parameter does not guarantee any particular properties. A constraint with extends states the minimum shape the function needs. The concrete input type is still preserved in its return value.

function keep<T extends { id: number }>(item: T): T {
  console.log(item.id);
  return item;
}
const member = keep({ id: 4, name: "Mina" });
console.log(member.name);

Output

4
Mina

Accept different compatible values

A length constraint can accept strings and arrays. It requires the shape, not one specific built-in type. Constraints describe relationships for the compiler; they do not check untrusted input at runtime.

function size<T extends { length: number }>(value: T): number {
  return value.length;
}
console.log(size("Hi") + size([1, 2, 3]));

Output

5

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Fix the task without using "any" or a type assertion, then check both practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Constrain a reusable size function

Add a constraint requiring a numeric "length" property to the type parameter of "size". Keep both calls.

Show solution
function size<T extends { length: number }>(value: T): number {
  return value.length;
}
const total = size("Hey") + size([2, 4]);
console.log(total);

The constraint permits reading length. Strings and arrays both satisfy it, while a number would be rejected by the compiler.

Practice