Course contentsShow
← TypeScript
Lesson 564 of 1,79613. GenericsFree lesson

The extends Keyword for Constraints

Learn how to constrain generic type parameters using extends to specify requirements.

The extends Keyword for Constraints

What you'll learn: How to use extends to restrict generic type parameters so they meet specific requirements.

Why Constraints Matter

In the previous lesson, you learned that generic type parameters sometimes need constraints. Without them, TypeScript assumes your type parameter could be anything, which limits what operations you can safely perform inside your generic code.

The extends keyword lets you say: "This type parameter can be any type, as long as it meets certain requirements."

Basic Constraint Syntax

Here's the pattern:

function example<T extends SomeType>(param: T): void {
  // Now TypeScript knows T has everything SomeType has
}

The constraint T extends SomeType means "T must be SomeType or a subtype of it."

Practical Example

function getLength<T extends { length: number }>(value: T): number {
  return value.length; // Safe! T is guaranteed to have 'length'
}

getLength("hello");        // Works: strings have length
getLength([1, 2, 3]);      // Works: arrays have length
getLength({ length: 5 });  // Works: object has length property
// getLength(42);          // Error: numbers don't have length

Without extends { length: number }, TypeScript would error on value.length because not all types have that property.

Think of It Like a Contract

The constraint is like saying: "I don't care exactly what type you give me, but it must have signed this contract (have these properties/capabilities)."

Key Takeaway: Use extends with type parameters to specify minimum requirements, enabling type-safe operations inside generic code while maintaining flexibility.