Sub topic 8
Default Type Parameters
This chapter assumes you can write a generic function, interface, or type alias with a type parameter, and that you know what extends constraints do. It covers how a type parameter gets a fallback type, where the fallback applies, and where it does not.
What a Default Does
A default type parameter gives a type parameter a value to use when the caller does not supply one. The syntax is = Type after the parameter name:
interface ApiResponse<T = unknown> {
data: T;
status: number;
}
const raw: ApiResponse = { data: "anything", status: 200 };
const typed: ApiResponse<string[]> = { data: ["a", "b"], status: 200 };ApiResponse written with no angle brackets means ApiResponse<unknown>. Without the default, the first declaration would fail with "Generic type 'ApiResponse' requires 1 type argument(s)".
Defaults solve two problems:
- They make the common case short. Callers who do not care about the type write nothing.
- They let you add a type parameter to an existing generic without breaking code that already uses it.
Choosing the Default Type
The default you pick decides how strict the unparameterized form is.
| Default | Effect on `ApiResponse` without arguments | Trade-off |
|---|---|---|
| `unknown` | `data` must be narrowed before use | Safe, slightly more work for callers |
| `any` | `data` can be used freely | No checking, errors surface at runtime |
| A concrete type such as `string` | `data` is a string | Convenient, but wrong if callers forget to override it |
Prefer unknown when no sensible concrete type exists. A default of any switches off checking for everyone who omits the argument.
function describe(res: ApiResponse): string {
if (typeof res.data === "string") {
return `text: ${res.data}`;
}
return `status ${res.status}`;
}
console.log(describe({ data: "ok", status: 200 })); // text: ok
console.log(describe({ data: 42, status: 200 })); // status 200Rules for Declaring Defaults
TypeScript enforces three rules.
- Required parameters cannot follow optional ones. Once a parameter has a default, every parameter after it needs a default too. This is the same ordering rule as for function parameters.
interface Bad<A = string, B>fails with "Required type parameters may not follow optional type parameters." - A default can refer to earlier parameters. It cannot refer to later ones.
- A default must satisfy the constraint. With
<T extends string = number>, the compiler reports thatnumberdoes not satisfy the constraintstring.
Here is the second rule in use:
type Pair<A, B = A> = [A, B];
const same: Pair<number> = [1, 2]; // B defaults to number
const mixed: Pair<number, string> = [1, "x"]; // B given explicitlyConstraints and defaults combine in one declaration, with the constraint first:
interface Entity {
id: number;
}
interface Repository<T extends Entity = Entity> {
find(id: number): T | undefined;
save(item: T): void;
}
interface User extends Entity {
name: string;
}
declare const anyRepo: Repository; // Repository<Entity>
declare const userRepo: Repository<User>;Defaults and Parameter Order
Callers can omit trailing arguments only. They cannot skip one in the middle. Put the parameter most callers will customize first, and the rarely changed ones after it, each with a default.
class Cache<V, K = string> {
private map = new Map<K, V>();
set(key: K, value: V): void {
this.map.set(key, value);
}
get(key: K): V | undefined {
return this.map.get(key);
}
}
const names = new Cache<number>(); // K is string
names.set("ada", 36);
const byId = new Cache<string, number>(); // K is number
byId.set(1, "Ada");Adding K = string later to a Cache<V> that already existed would not break any existing Cache<number> usage. That is the backward-compatibility benefit.
Defaults Versus Inference
A default is not used whenever inference is possible. For a generic function, TypeScript first looks for candidates in the arguments. The default applies only when there are none.
function wrap<T = string>(value?: T): T[] {
return value === undefined ? [] : [value];
}
const a = wrap(5); // number[] (inferred from the argument)
const b = wrap(); // string[] (no candidate, so the default)
const c = wrap<boolean>(); // boolean[] (explicit)The same function without a default would give unknown[] for wrap(). When a constraint exists but no default, an un-inferrable parameter falls back to the constraint.
The next diagram shows the order in which TypeScript decides the type for one type parameter.
Explicit Arguments Switch Off Inference for the Rest
TypeScript has no partial inference. If you write some type arguments, it does not infer the others from the call. The remaining parameters take their defaults, and a parameter without a default is an error.
function pairUp<T, U = string>(first: T, second?: U): [T, U | undefined] {
return [first, second];
}
const p1 = pairUp(1, true); // [number, boolean | undefined], U inferred
const p2 = pairUp<number>(1, "x"); // U is the default, string
// const p3 = pairUp<number>(1, true); // Error: boolean is not assignable to string
// const p4 = pairUp<number, string, boolean>(1); // Error: expected 1-2 type argumentsIf you want inference for some parameters, either give all arguments explicitly or restructure the function. A common restructure is a curried helper that fixes one type first and lets the inner call infer the rest.
Common Errors
- Omitting arguments with no default.
interface Box<T>used asBoxis an error. Add a default or writeBox<number>. - Empty angle brackets.
ApiResponse<>is a syntax error. Drop the brackets. - Expecting the default to win over inference. In
wrap(5), the defaultstringis ignored becausenumberwas inferred. If you want the default to win, annotate the parameter or callwrap<string>(...). - Using
anyas the default. It hides mistakes for everyone who omits the argument. Useunknown. - A default that fails the constraint. The error appears on the default itself, not at the call site.
Design Criteria
Add a default when at least one of these holds:
- Most callers would write the same type argument, such as
stringfor a map key. - You are adding a type parameter to a public generic and need existing callers to keep compiling.
- The type has a safe "unknown" form, such as
ApiResponseholding an unvalidated payload.
Skip the default when callers must make a deliberate choice. A Repository<T> where forgetting T silently gives you the base Entity type may let bugs through. A required parameter forces the decision and makes the omission a compile error.
Exercise
Given type Result<T = string, E = Error> = { ok: true; value: T } | { ok: false; error: E };, what are the types of Result, Result<number>, and Result<number, string>? Then say whether type Bad<T = string, E> = ... is allowed.
Show answer
Result is Result<string, Error>. Result<number> is Result<number, Error> because E takes its default. Result<number, string> has no defaults applied. type Bad<T = string, E> is not allowed, because a required type parameter (E) cannot follow an optional one (T). The fix is to give E a default, or to move E before T.
Exercise
What does each call return in the type system? function make<T = number>(value?: T): T[] { return value === undefined ? [] : [value]; } const x = make("a"); const y = make(); const z = make<string>();
Show answer
x is string[], because inference from the argument "a" takes precedence over the default. y is number[], because there is no inference candidate and the default number applies. z is string[], because the explicit type argument overrides the default.