Web Analytics

Generic Constraints

Intermediate~22 min

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
  • keyof creates union of property keys
  • Ensures type safety while maintaining flexibility
  • Perfect for property access and object manipulation