Tsallaka zuwa abun ciki
Justice Tech School

Generic Constraints and Defaults

T extends X limits what T can be. keyof T gives the property names, and T[K] looks up a property type. Default type parameters add convenience.

Example
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
const user = { name: "Ada", age: 21 };
console.log(getProp(user, "name"), getProp(user, "age"));
interface Box<T = string> { value: T }
const b: Box = { value: "hi" };
console.log(b.value);

Result

Ada 21
hi

Exercise

Property names of T.

K extends  T

Quiz Test

What does keyof T give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.