Default Type Parameters
In this page:
interface InterfaceName<T = DefaultType> {
value: T;
}
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);
- Placing a required type parameter after one with a default, like
<T = string, U>, which is an error because defaulted parameters must come last. - Writing
Box<>or expecting the default to apply when you give a wrong argument, when a default only fills in a missing argument. - Assuming the default is used when TypeScript can infer
T, when inference from a function argument wins over the default.
- Generics let functions, interfaces, and classes work with many types while keeping type safety.
- Constraints with
extendsand thekeyofoperator limit what a type parameter can be. - Classes and functions can use multiple type parameters and default type parameters for flexible reusable code.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: