Sub topic 8
Giving type parameters a default
This chapter assumes you can write and call simple generic functions such as identity<T>(x: T): T. It also assumes you know interfaces, type aliases, and union types. Constraints with extends are covered in earlier chapters. This chapter does not depend on them, and the interaction between defaults and constraints comes in the next chapter.
Why defaults exist
A type parameter is a placeholder that the caller fills in. Without a default, every use of a generic interface or type alias must supply every type argument. That becomes tedious when most callers want the same types.
interface ApiResponse<TData, TError> {
data?: TData;
error?: TError;
}
// const r: ApiResponse = {};
// Error: Generic type 'ApiResponse' requires 2 type argument(s).
const r: ApiResponse<unknown, Error> = {}; // legal, but repetitiveA default type parameter is a type written after = in the parameter list. TypeScript uses it when the caller does not provide that argument and, for functions and classes, when inference finds nothing to use.
interface ApiResponse<TData = unknown, TError = Error> {
data?: TData;
error?: TError;
}
const a: ApiResponse = {}; // TData = unknown, TError = Error
const b: ApiResponse<string> = { data: "ok" }; // TError is still Error
const c: ApiResponse<string, { code: number }> = { error: { code: 404 } };The three declarations show the behavior:
ApiResponsewith no arguments uses both defaults.ApiResponse<string>sets the first parameter and leaves the second at its default.ApiResponse<string, { code: number }>overrides both.
Where you can declare defaults
Defaults are allowed on every kind of generic declaration: interfaces, type aliases, classes, and functions. The syntax is the same in each.
// Interface (shown above): interface ApiResponse<TData = unknown, TError = Error>
// Type alias
type Constructor<T = object> = new (...args: any[]) => T;
// Class
class Stack<T = string> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
// Function
function createList<T = string>(): T[] {
return [];
}
const s = new Stack(); // Stack<string>
const n = new Stack<number>(); // Stack<number>
const xs = createList(); // string[]
const ys = createList<boolean>(); // boolean[]Each of these is a different situation:
- Type alias.
Constructorwith no argument describes a constructor that returnsobject.Constructor<Point>describes one that returnsPoint. - Class.
new Stack()has no constructor arguments, so nothing lets TypeScript inferT. It uses the defaultstring. - Function.
createList()has no parameters that mentionT, soTalso falls back to its default.
Here is Constructor used in a function. The class you pass in determines the instance type:
type Constructor<T = object> = new (...args: any[]) => T;
function createInstance<T>(ctor: Constructor<T>): T {
return new ctor();
}
class Point {
x = 0;
y = 0;
}
const p = createInstance(Point); // type: PointHere the default of Constructor is never used. createInstance passes T explicitly, and inference fills it in from Point. The default only matters when someone writes plain Constructor, for example as a parameter type for "any class."
Defaults can refer to earlier parameters
A default may use any type parameter declared before it in the same list. This lets one parameter follow another unless the caller says otherwise.
interface Pair<A, B = A> {
first: A;
second: B;
}
const same: Pair<number> = { first: 1, second: 2 }; // B is number
const mixed: Pair<number, string> = { first: 1, second: "two" }; // B overriddenThe reverse is an error. A default cannot refer to a parameter that comes later:
// interface Bad<A = B, B = string> {}
// Error: Type parameter defaults can only reference previously declared type parameters.The reason is that TypeScript resolves the list from left to right. When it reaches A, B has no value yet.
The ordering rules
Two rules govern how you write the list.
- Required parameters must come before optional ones. A parameter without a default cannot follow one that has a default.
- Callers can omit only trailing arguments. You cannot skip a middle argument and supply a later one.
// interface Bad2<A = string, B> {}
// Error: Required type parameters may not follow optional type parameters.
interface Good<A, B = string, C = number> {
a: A;
b: B;
c: C;
}
type G1 = Good<boolean>; // B = string, C = number
type G2 = Good<boolean, Date>; // C = number
type G3 = Good<boolean, string, bigint>; // everything explicitTo set C you must also write B, even when you want B's default. Repeat the default value yourself:
type G4 = Good<boolean, string, bigint>; // B written out to reach CAn empty argument list is also an error. Good<> does not mean "use all defaults." Write Good<boolean> or, if every parameter has a default, just the bare name.
The ordering rule has a consequence for design. Put the parameters callers must always choose first. Put the ones most callers can ignore last, and order the optional ones by how often callers need to change them.
Evolving an API with defaults
Defaults let you add a type parameter to an existing generic type without breaking its users. Suppose a library ships this:
interface Result<T> {
value?: T;
}
const old: Result<string> = { value: "x" };Later you want to let callers say what the error type is. Adding E = Error keeps every existing Result<string> valid and means the same thing as before:
interface Result<T, E = Error> {
value?: T;
error?: E;
}
const stillValid: Result<string> = { value: "x" };
const newStyle: Result<string, { code: number }> = { error: { code: 500 } };Without the default, every Result<string> in every consumer would fail with "requires 2 type arguments." Adding a new parameter with a default is a non-breaking change. Adding one without a default is a breaking change.
Choosing a good default
The default should be what most callers would write anyway. Some common choices:
| Default | Use it when | Trade-off |
|---|---|---|
| `unknown` | The caller should decide, and you want safety until they do | Values must be narrowed before use |
| `any` | You need maximum compatibility, such as in a `Constructor` argument list | Turns off type checking for that position |
| `never` | The parameter is an optional extension, such as an "extra events" type | Values of that type cannot exist, which makes it a good "nothing here" marker |
| A concrete type such as `string` | One type covers the common case | Callers wanting a different type must write it out |
| An earlier parameter, as in `B = A` | The two usually match | Harder to read at call sites |
Prefer unknown to any unless you have a specific reason. A default of any lets unchecked values flow through silently.
What a default does and does not do
A default is not a restriction. It says what to use when the caller says nothing, not what the caller is allowed to say. Callers can still override it with anything:
type Wrapper<T = string> = { value: T };
const w1: Wrapper = { value: "hi" }; // default string
const w2: Wrapper<number> = { value: 1 }; // allowed: the default is not a limitTo limit what callers may pass, you need a constraint with extends. The next chapter covers how the two features combine and what the compiler checks.
A default also does not change how a value behaves at runtime. Type parameters are erased when TypeScript compiles to JavaScript, so Stack<string> and Stack<number> are the same class at runtime.
How defaults meet inference
For type aliases and interfaces, there is no inference. You write the arguments or you get the defaults. For functions and classes, TypeScript first tries to infer each parameter from the arguments you pass. A default only matters when inference has nothing to work with.
function wrap<T = string>(value?: T): { value?: T } {
return { value };
}
const a = wrap(); // no candidates for T, so the default applies: string
const b = wrap(42); // inferred from the argument: number
const c = wrap<boolean>(); // explicit argument overrides everything: booleanThe same pattern appears with a parsing helper:
function parse<T = unknown>(json: string): T {
return JSON.parse(json) as T;
}
const a = parse("1"); // T has no inference candidates, so the default applies: unknown
const b = parse<number>("1"); // T is set explicitly: numberWatch out for b. The call compiles, but nothing checks that the JSON really holds a number. The as T assertion trusts the caller. A default of unknown is a good guard here, because the unannotated call returns a value you cannot use without narrowing it.
The order TypeScript follows for a single type parameter can be summarized like this:
The last branch matters for functions. A function without a default and without inference candidates gets unknown, which is what parse would get if you removed = unknown. The default there documents the choice. In createList, the default string changes the result from unknown[] to string[]. The next-but-one chapter returns to the cases where inference and defaults disagree.
Common mistakes
- Putting a required parameter after an optional one. This produces "Required type parameters may not follow optional type parameters." Reorder the list.
- Expecting
Foo<, X>to skip a parameter. Skipping is not supported. Write out the default value for the skipped position. - Using
anyas a convenience default. It makes every unannotated use unchecked. Useunknown. - Treating the default as a limit.
Wrapper<number>is legal when the default isstring. - Referencing a later parameter in a default. Defaults can only look backward in the list.
- Assuming a default fixes the result of inference. If an argument supplies a candidate, TypeScript uses it and ignores the default.
Exercise
You have interface Cache<TKey, TValue = string, TTTL = number> { get(key: TKey): TValue | undefined; }. Which of these is invalid, and why? (1) Cache<number> (2) Cache<number, boolean> (3) Cache<number, , Date> (4) Cache<>
Show answer
(3) and (4) are invalid. TypeScript does not allow an omitted argument in the middle of the list, so to set TTTL you must write Cache<number, string, Date>. An empty argument list is also an error because TKey is required. (1) is valid and means Cache<number, string, number>. (2) is valid and means Cache<number, boolean, number>.
Exercise
Given function make<T = number>(init?: T): T[] { return init === undefined ? [] : [init]; }, what are the types of make(), make("a"), and make<boolean>()?
Show answer
make() is number[], because there is no candidate for T and the default applies. make("a") is string[], because T is inferred from the argument and the default is ignored. make<boolean>() is boolean[], because the explicit type argument overrides both inference and the default.
Exercise
A library exports interface Event<TPayload> { payload: TPayload } and many consumers write Event<string>. You want to add TMeta so consumers can attach metadata. How do you add it without breaking anyone, and which kind of default would you choose?
Show answer
Declare interface Event<TPayload, TMeta = unknown> { payload: TPayload; meta?: TMeta }. Existing Event<string> usages still compile because TMeta has a default. A default of unknown is a good choice because it forces new code to narrow the metadata before using it, and any would silently skip checking.