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

When to Use Defaults vs Required Parameters

Decide between requiring explicit type arguments and providing sensible defaults.

When to Use Defaults vs Required Parameters

You'll learn when to require explicit type arguments and when sensible defaults make your generics easier to use.

The Two Approaches

Generic type parameters can either be required (forcing callers to specify them explicitly) or have defaults (automatically filled in when not provided). The choice shapes your API's usability and safety.

Required parameters force clarity:

function createPair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

// Must infer or specify both T and U
const pair = createPair(42, "hello");

Default parameters provide convenience:

function createContainer<T = string>(value: T): { data: T } {
  return { data: value };
}

// T defaults to string
const container1 = createContainer("text");

// But you can override the default
const container2 = createContainer<number>(42);

When to Require Type Arguments

Use required parameters when:

  • Inference fails: The type parameter doesn't appear in function arguments
  • Multiple valid choices exist: No single default makes sense for all use cases
  • Explicitness prevents errors: You want callers to think carefully about the type

When to Provide Defaults

Use default parameters when:

  • A common case dominates: 80% of usage needs the same type
  • Backward compatibility matters: Adding defaults doesn't break existing code
  • The default is genuinely sensible: It's not arbitrary—it reflects real typical usage

Key Takeaway: Use required type parameters when explicitness prevents mistakes; use defaults when a common-sense fallback improves ergonomics without sacrificing safety.