Constraints

Constrain with extends

A constraint sets the minimum shape a type argument must have. The extends keyword draws that line. Below, T must carry a length property, so numbers are rejected while strings and arrays pass.

function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } console.log(longest("abc", "de"));

abc

Keys with keyof

The keyof operator builds a union of the property names of an object type. Pair it with a constraint so the key argument must exist on the object. Typos in property names become compile errors instead of undefined at runtime.

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const user = { name: "Ada", age: 36 }; console.log(getProp(user, "age"));

36

Default type params

A default type argument applies when the caller names no type and inference finds nothing. Write it with an equals sign after the parameter. Defaults keep generic helpers usable with zero angle brackets in the common case.

type Box<T = string> = { value: T }; const a: Box = { value: "hi" }; const b: Box<number> = { value: 3 }; console.log(a.value); console.log(b.value);

hi

3

Where constraints live

Constraints belong on the declaration, right after each type parameter, never at the call site. Callers simply pass values and let the checker compare. When a call fails, read the constraint first because it states the exact rule that was broken.

interface Labeled { label: string; } function printLabel<T extends Labeled>(item: T): void { console.log(item.label); } printLabel({ label: "Box" });

Box

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does T extends { length: number } require of a type argument?

    Answer

    It must have a length property of type number

    The constraint names the minimum shape, so strings and arrays pass and numbers do not.

  2. What does keyof T produce?

    Answer

    A union of the property names of T

    The operator turns the keys into a union, which is why a typo can be checked against it.

  3. When does a default type argument apply?

    Answer

    When the caller names no type and inference finds nothing

    The written type argument wins, and the default fills the gap when there is none.

  4. Where does a constraint belong?

    Answer

    On the declaration, after the type parameter

    The declaration states the rule once, and every call is checked against it.

  5. What does this program print? function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } console.log(longest("abcd", "ab"));

    Answer

    abcd

    The longer string has four characters, so the first argument is returned.

  6. What does this program print? function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const user = { name: "Ada", age: 36 }; console.log(getProp(user, "name"));

    Answer

    Ada

    The key names a real property, and the function returns its value.

  7. What does this program print? type Box<T = string> = { value: T }; const a: Box = { value: "hi" }; console.log(a.value);

    Answer

    hi

    The missing type argument falls back to the default, string, so the text is accepted.

  8. What does the compiler say about this program? function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } console.log(longest(1, 2));

    Answer

    error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

    A number has no length, so it does not meet the constraint of the type parameter.

  9. What does the compiler say about this program? function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const user = { name: "Ada", age: 36 }; console.log(getProp(user, "nmae"));

    Answer

    error TS2345: Argument of type '"nmae"' is not assignable to parameter of type '"name" | "age"'.

    The key union holds the real names, so the typo is rejected at the call.

  10. What does this program print? interface Labeled { label: string; } function printLabel<T extends Labeled>(item: T): void { console.log(item.label); } printLabel({ label: "Box" });

    Answer

    Box

    The object satisfies the constraint, and the function prints its label.

Article author: Arthur Isaev