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

Default Type Parameters

Provide fallback types for generics using default type parameter syntax with equals.

Default Type Parameters

What you'll learn: How to provide fallback types for generic type parameters so they don't need to be specified every time.

The Problem: Required Type Arguments

When you create a generic type or function, you usually need to specify the type parameter explicitly or rely on inference. But sometimes you want a "default choice" — a sensible fallback when the caller doesn't provide a specific type.

Default Type Parameter Syntax

TypeScript lets you assign default types to type parameters using the = operator, similar to how default parameter values work in regular functions:

type Container<T = string> = {
  value: T;
};

// Uses the default: string
const a: Container = { value: "hello" };

// Explicit override
const b: Container<number> = { value: 42 };

How It Works

The equals sign after the type parameter name provides a fallback. If no type argument is supplied (and inference doesn't determine a type), TypeScript uses the default.

function wrap<T = number>(value: T): { data: T } {
  return { data: value };
}

// Inferred as number (from default)
const x = wrap(10);

// Explicitly overridden as string
const y = wrap<string>("text");

Combining Defaults with Constraints

You can use defaults alongside constraints. The default must satisfy the constraint:

type Response<T extends object = { status: number }> = {
  data: T;
};

// Uses default object shape
const res1: Response = { data: { status: 200 } };

// Custom type
const res2: Response<{ name: string }> = { data: { name: "API" } };

Multiple Defaults

When you have multiple type parameters, defaults can reference earlier parameters:

type Pair<K = string, V = K> = {
  key: K;
  value: V;
};

// Both default to string
const p: Pair = { key: "id", value: "name" };

Key Takeaway: Default type parameters let you specify fallback types using =, making generics more convenient while maintaining the flexibility to override when needed.