← Back to TypeScript Course | Chapter 7: Generics | Lesson 8 of 8

Default Type Parameters

Default type parameters provide a fallback type for a generic parameter when the caller does not specify one. They make generic APIs easier to use while still allowing callers to choose another type.

Basic Default Type Parameter

A default type is assigned after the type parameter using an equals sign (T = string, for example), and that default is used automatically whenever the caller doesn't supply a type argument.

Example: Basic Default Type Parameter

typescript
interface Box<T = string> {
  value: T;
}
const b: Box = { value: "hello" };
console.log(b.value);

Overriding the Default

A default type can always be overridden by explicitly supplying another type argument at the call site, so the default is purely a convenience for the common case, not a hard restriction.

Example: Overriding the Default

typescript
interface Box<T = string> {
  value: T;
}
const b: Box<number> = { value: 42 };
console.log(b.value);

Default Types in Generic Functions

Generic functions can define defaults, which is useful when a particular type should be assumed unless the caller has a specific reason to deviate from it.

Example: Default Types in Generic Functions

typescript
function wrap<T = string>(value: T): T[] {
  return [value];
}
console.log(wrap("hi"));
console.log(wrap<number>(5));

Default Types in Classes

Generic classes can provide defaults so the common, everyday use of the class doesn't require writing out an explicit type argument every single time it's instantiated.

Example: Default Types in Classes

typescript
class Container<T = string> {
  constructor(public value: T) {}
}
const c = new Container("default");
console.log(c.value);

Multiple Default Type Parameters

A generic declaration can have several default type parameters at once, though any required (non-default) type parameters must always come before the ones that have defaults, matching how default function parameters work.

Example: Multiple Default Type Parameters

typescript
interface Pair<A, B = string, C = number> {
  first: A;
  second: B;
  third: C;
}
const p: Pair<boolean> = { first: true, second: "x", third: 1 };
console.log(p);
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.