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");