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

Combining Constraints and Defaults

Use both extends constraints and default values together for flexible yet safe generics.

Combining Constraints and Defaults

You'll learn how to use extends constraints together with default type parameters to create generics that are both flexible and safe.

The Best of Both Worlds

So far, you've seen constraints that enforce what types are allowed, and defaults that provide fallback types when none are specified. When you combine these two features, you get a powerful pattern: constrained defaults.

This means you can say: "If the caller doesn't provide a type, use this default—but whatever they do provide must meet these requirements."

How It Works

The syntax layers both features together:

function createContainer<T extends object = { id: number }>(
  value: T
): T {
  return value;
}

// Uses default: { id: number }
const container1 = createContainer({ id: 1 });

// Custom type, but must extend object
const container2 = createContainer({ id: 2, name: "Alice" });

// Error: number doesn't extend object
// const container3 = createContainer(42);

The constraint (extends object) applies to both the default and any explicitly provided types. This ensures type safety even when using the fallback.

Common Pattern: API Response Wrappers

interface BaseResponse {
  status: number;
}

function wrapResponse<T extends BaseResponse = BaseResponse>(
  data: T
): { data: T; timestamp: number } {
  return { data, timestamp: Date.now() };
}

// Uses default BaseResponse
const basic = wrapResponse({ status: 200 });

// Custom, but must have status
const detailed = wrapResponse({ status: 200, body: "OK" });

The default provides a sensible baseline, while the constraint ensures all variations remain compatible with your API's contract.

Key Takeaway: Combining extends constraints with default type parameters lets you provide convenient defaults while enforcing safety rules—giving callers flexibility without sacrificing type guarantees.