📘
Advanced Generics: Constraints and Defaults
Intermediate
110 XP
45 min
Lesson Content
Advanced Generics
Learn to constrain generics and provide defaults for more powerful type-safe code.
Generic Constraints
interface Lengthwise {
length: number;
}
function logLength(arg: T): T {
console.log(arg.length);
return arg;
}
logLength("hello"); // OK - string has length
logLength([1, 2, 3]); // OK - array has length Default Type Parameters
function createArray(length: number, value: T): T[] {
return Array(length).fill(value);
} Keyof Constraint
function getProperty(obj: T, key: K): T[K] {
return obj[key];
} Example Code
Use constraints and keyof
function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "John", age: 30 };
console.log(getValue(user, "name"));
console.log(getValue(user, "age"));Expected Output:
John 30
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code