Generic Constraints
Generic constraints limit type parameters to specific types using extends, ensuring type safety while maintaining flexibility.
Constraints with Extends
Output
Click Run to execute your code
Constraint Syntax: Use
<T extends Type> to constrain T to types that extend or
implement Type.keyof Constraint
The keyof operator creates a union of all property keys:
function getValue(obj: T, key: K): T[K] {
return obj[key]; // Type-safe property access
}
Common Mistakes
1. No Constraint When Needed
// โ Error - T might not have length
function logLength(item: T) {
console.log(item.length); // Error!
}
// โ Correct - constrain to types with length
function logLength(item: T) {
console.log(item.length); // โ OK
}
2. Wrong keyof Usage
// โ Wrong - allows any string
function get(obj: T, key: string) {
return obj[key]; // Unsafe!
}
// โ Correct - only valid keys
function get(obj: T, key: K) {
return obj[key]; // Type-safe!
}
Best Practice: Use constraints to ensure
generic types have required properties or methods.
Summary
- Constraints limit type parameters with
extends keyofcreates union of property keys- Ensures type safety while maintaining flexibility
- Perfect for property access and object manipulation
Enjoying these tutorials?