Lesson 11 of 15
Generic Constraints
Generic Constraints
Sometimes you need a generic that accepts any type — but only types with certain properties. Use extends to constrain the type parameter:
interface HasLength {
length: number;
}
function longest<T extends HasLength>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest("hello", "hi")); // hello
console.log(longest([1, 2, 3], [1, 2])); // [1, 2, 3]
T extends HasLength means: T can be any type that has a length: number property. Both string and Array qualify.
keyof Constraint
keyof T is the union of a type's property names. It lets you write functions that safely access an object's properties:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Alice", age: 30 };
console.log(getProperty(user, "name")); // Alice
console.log(getProperty(user, "age")); // 30
// getProperty(user, "missing"); // Error: not a key of user
Your Task
Write function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] and use it to access properties of an object.
TypeScript loading...
Loading...
Click "Run" to execute your code.