Sikau

TypeScript · Day 15 · about 25 min

Generic constraints

extends and keyof.

Any type — but with rules

Sometimes "any type" is too much: a function that reads .length needs things that *have* a length. Constraints say "T can be anything that has…".

extends and keyof

function longest<T extends { length: number }>(a: T, b: T): T {
  return b.length > a.length ? b : a;
}
longest("momo", "thukpa");
longest([1, 2], [3]);
longest(10, 20);

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user = { name: "Asha", age: 21 };
const age = getProp(user, "age");
getProp(user, "email");

The rest of this lesson

  • Why constrainexplain
  • keyof and indexed accessexplain
  • What's keyof?predict
  • Read the typematch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript