Default Type Parameters
In this page:
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
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
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
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
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
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: