0Pricing
TypeScript Academy · Lesson

Generic Constraints with extends

Restrict type parameters to specific shapes.

Welcome

Generic constraints narrow what types can be passed as type arguments. Use `extends` to require that T has certain properties or matches a certain shape.

The Problem Without Constraints

Without constraints, TypeScript doesn't know what operations are valid on T, so it only allows operations common to all types.
function getLength<T>(val: T): number {
  // return val.length; // Error — T might not have .length
}

All lessons in this course

  1. Generic Functions: Type Parameters
  2. Generic Interfaces and Type Aliases
  3. Generic Constraints with extends
  4. Default Type Parameters
← Back to TypeScript Academy