Sub topic 9
Combining Defaults with Constraints, and the Ordering Rules
Constraints and defaults are separate features, but they often appear on the same type parameter. T extends string = "a" says two things: which types are allowed, and which one to use when the caller says nothing. This chapter covers how the two interact, the rules TypeScript enforces on a parameter list, and the errors you will see when you break them.
This chapter assumes you can write generic functions and interfaces, and that you have met extends constraints and default type parameters on their own. You should also know that keyof T produces a union of property names.
A constraint and a default answer different questions
A constraint is a filter. It decides which type arguments are legal, whether the caller writes them or TypeScript infers them. A default is a fallback. It decides which type to use when the caller omits the argument and nothing can be inferred.
The two meet at one point: the fallback must pass the filter. A default is itself a type argument that TypeScript supplies for you, so it gets the same check a hand-written argument would get.
type Box<T extends string | number = string> = { value: T };
const s: Box = { value: "hi" }; // T defaults to string
const n: Box<number> = { value: 1 }; // T is number
// const x: Box<boolean> = { value: true }; // Error: boolean does not satisfy the constraintBox with no argument uses string, which is a member of string | number. An explicit boolean fails the constraint. The default does not have to equal the constraint. It only has to be assignable to it. A narrow default inside a wide constraint is the usual pattern.
Rule 1: the default must satisfy the constraint
TypeScript checks the default against the constraint at the declaration, not at the use site. You find out when you write the declaration.
// type Bad1<T extends string = number> = T;
// Error: Type 'number' does not satisfy the constraint 'string'.
type Ok1<T extends string = "left"> = T; // a literal is assignable to string
type Ok2<T extends object = { id: number }> = T;If the parameter has no extends clause, its constraint is effectively unknown, so any default is accepted.
A default can also depend on an earlier parameter. In that case the check runs against the constraint with the earlier parameter in place:
type Fields<T extends object, K extends keyof T = keyof T> = Pick<T, K>;
interface User {
id: number;
name: string;
email: string;
}
type Full = Fields<User>; // id, name and email
type Summary = Fields<User, "id" | "name">; // id and name only
// type Wrong = Fields<User, "age">; // Error: "age" is not a key of Userkeyof T is always assignable to keyof T, so the declaration is accepted for every T. Here the default says "all keys unless you narrow it", and the constraint says "never a key that does not exist".
Rule 2: required parameters cannot follow optional ones
A type parameter with a default is optional. A parameter without one is required. TypeScript forbids a required parameter after an optional one.
// interface Bad2<A = string, B> {}
// Error: Required type parameters may not follow optional type parameters.
interface Good<B, A = string> {} // required first, optional last
interface AlsoGood<A = string, B = number> {} // all optionalThe reason is positional syntax. Type arguments are matched by position, and you cannot skip one. If A were optional and B required, Bad2<number> would be ambiguous: it could mean A = number with B missing, or B = number with A defaulted. The rule removes the ambiguity. Callers fill parameters left to right, and defaults only cover a trailing run.
Constraints do not matter for this rule. A parameter with extends but no = is required, and it still has to come before any parameter that has a default.
interface Store<TKey extends string, TValue = unknown> {
get(key: TKey): TValue | undefined;
}
declare const s1: Store<"a" | "b">; // TValue = unknown
declare const s2: Store<"a" | "b", number>; // TValue = numberRule 3: a default may only refer to earlier parameters
A default can use any parameter declared to its left. It cannot use one declared to its right, and it cannot refer to itself.
type Pair<A, B = A> = [A, B];
type P1 = Pair<number>; // [number, number]
type P2 = Pair<number, string>; // [number, string]
// type Bad<A = B, B = string> = [A, B];
// Error: Type parameter defaults can only reference previously declared type parameters.Constraints are less strict than defaults here. A constraint may mention a parameter declared later, because constraints are resolved together once all names exist. Only circular constraints (A extends B, B extends A) are rejected. Defaults are evaluated in order, so they can only look backward.
The three rules together:
| Rule | Allowed | Rejected | Error message (abridged) |
|---|---|---|---|
| Default satisfies constraint | `T extends string = "a"` | `T extends string = number` | Type 'number' does not satisfy the constraint 'string' |
| Required before optional | `<B, A = string>` | `<A = string, B>` | Required type parameters may not follow optional type parameters |
| Default refers backward only | `<A, B = A>` | `<A = B, B = string>` | Type parameter defaults can only reference previously declared type parameters |
The diagram below shows the order in which you can check a parameter list by hand.
A default computed from another parameter
The most useful combination is a constrained parameter followed by a parameter whose default is derived from it. The spine's repository example does this:
interface Repository<
T extends { id: string },
TCreate = Omit<T, "id">
> {
create(input: TCreate): T;
findById(id: string): T | undefined;
}
interface Book {
id: string;
title: string;
}
declare const books: Repository<Book>; // create takes { title: string }
declare const drafts: Repository<Book, { title?: string }>; // caller overrides the defaultT is required and constrained, so it comes first. TCreate is optional and refers back to T. The common case needs one type argument. The unusual case, where creation takes a different shape, needs two, and nothing about the first case gets harder.
Here TCreate has no constraint. If you added one, such as TCreate extends object = Omit<T, "id">, the compiler would have to prove that Omit<T, "id"> is assignable to object for every possible T. That usually works, but with complex derived types the proof can fail. Add a constraint to a defaulted parameter only when the body needs to rely on it.
Defaults on every kind of declaration
Defaults and constraints work on interfaces, type aliases, classes, and functions. The ordering rules are the same on all four.
class Cache<K extends string | number = string, V = unknown> {
private store = new Map<K, V>();
set(key: K, value: V): void {
this.store.set(key, value);
}
get(key: K): V | undefined {
return this.store.get(key);
}
}
const loose = new Cache(); // Cache<string, unknown>
const ids = new Cache<number, string>(); // Cache<number, string>
loose.set("a", 1);
ids.set(7, "seven");With new Cache() there is no argument for the compiler to infer from, so both parameters take their defaults. This is the "no inference candidates" case, which the next chapter studies in more detail.
Partial type arguments do not trigger inference
This is the gotcha that most often surprises people. For a function call, you either let TypeScript infer all type arguments or you write all the ones that lack defaults. If you write some of them, the rest are not inferred. They take their defaults, or the call is an error if there is no default.
function makeEntry<K extends string, V = unknown>(
key: K,
value: V
): { key: K; value: V } {
return { key, value };
}
const e1 = makeEntry("a", 1); // { key: "a"; value: number }
const e2 = makeEntry<"a">("a", 1); // { key: "a"; value: unknown }
const e3 = makeEntry<"a", number>("a", 1); // { key: "a"; value: number }In e1 everything is inferred. In e2 the caller named K, so V is no longer inferred. It falls back to its default, unknown, and the value type is lost. If V had no default, makeEntry<"a">(...) would be an error: expected 2 type arguments, but got 1.
This is the main practical cost of giving a function type parameter a default. A default can quietly replace an inferred type once a caller supplies any explicit argument.
Defaults, constraints, and what an omitted argument means
When a type argument is missing, TypeScript picks a source in a fixed order. The next chapter walks through inference in depth. For this chapter, remember three points:
- On a type alias, interface, or class type annotation (
Box,Repository<Book>), there is no inference. A missing argument must have a default, otherwise it is an error ("Generic type 'Box' requires 1 type argument"). - On a function call with no explicit arguments, TypeScript infers from the call's arguments. If inference finds nothing, it uses the default. If there is no default either, it uses the constraint, or
unknownwhen there is no constraint. - The default is never used to reject an inferred type. Only the constraint can reject one.
The last point means a default is a suggestion, while a constraint is a requirement. A parameter T extends string = "a" accepts "b", string, or any string literal union. The default only matters when nothing else decides the type.
A worked design: constraint and default together
This Result type combines everything above. The success type is required. The error type is constrained to Error and defaults to plain Error.
type Result<TValue, TError extends Error = Error> =
| { ok: true; value: TValue }
| { ok: false; error: TError };
class HttpError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
function fail<TError extends Error = Error>(error: TError): Result<never, TError> {
return { ok: false, error };
}
const r1: Result<string> = { ok: true, value: "done" }; // TError = Error
const r2 = fail(new HttpError(404, "Not found")); // TError inferred as HttpError
const r3: Result<number, HttpError> = fail(new HttpError(500, "Boom"));
if (!r2.ok) {
console.log(r2.error.status); // 404, typed as number
}Result<string> is easy to write for the simple case. fail infers the specific error class, so r2.error.status is available without a cast. The constraint blocks Result<string, number>, because number is not an Error. The default is Error, which is exactly the constraint here. That is fine and common when the constraint is a sensible baseline.
Common mistakes
- Putting a defaulted parameter before a required one. Reorder so required parameters come first, even if the "natural" reading order differs.
- Choosing a default that is wider than the constraint.
T extends string = string | numberfails Rule 1. - Referring forward in a default. If two defaults depend on each other, one of them should become required.
- Expecting a function default to apply alongside inference. An explicit partial list switches inference off for the remainder.
- Adding a constraint to a defaulted parameter "for safety" when nothing in the body uses it. The constraint then only narrows what callers can pass.
Exercise
This declaration produces two errors. Name both rules it breaks, then rewrite it so it compiles and so that Query<User> means Query<User, keyof User>.
type Query<K extends keyof T = keyof T, T extends object> = Pick<T, K>;
interface User { id: number; name: string }
Show answer
It breaks the ordering rule, because K has a default but T after it is required ("Required type parameters may not follow optional type parameters"). It also breaks the backward-reference rule, because the default keyof T refers to T, which is declared later. Move T first: type Query<T extends object, K extends keyof T = keyof T> = Pick<T, K>;. Now Query<User> is Pick<User, "id" | "name">, and Query<User, "id"> narrows it. The constraint on K may refer to T either way, but the default may only refer backward.
Exercise
Given function tag<K extends string, V = unknown>(key: K, value: V): [K, V], what is the type of tag<"x">("x", 42), and why is it not ["x", number]?
Show answer
It is ["x", unknown]. The caller supplied an explicit type argument for K, so TypeScript does not infer V from the argument 42. It uses the default, unknown. Writing tag("x", 42) infers ["x", number], and tag<"x", number>("x", 42) also gives ["x", number].