Sub topic 9
Combining Defaults with Constraints, and the Ordering Rules
This chapter assumes you know basic TypeScript interfaces, type aliases, unions, generic functions, keyof, and indexed access types such as T[K].
A generic constraint limits the types that a type parameter may represent. A default type supplies a value for that parameter when the caller leaves it out. These features work together, but they follow separate rules.
A default must satisfy its constraint
Use extends to constrain a type parameter, then place = Type after the constraint to give it a default:
type Box<T extends string | number = string> = {
value: T;
};
const textBox: Box = { value: "hello" };
// T defaults to string
const numberBox: Box<number> = { value: 42 };
// T is explicitly number
// const badBox: Box<boolean> = { value: true };
// Error: boolean does not satisfy string | numberThe default string is valid because string satisfies the constraint string | number. A default that violates its constraint is rejected:
// type Invalid<T extends string = number> = T;
// Error: number does not satisfy the constraint stringThe constraint and the default have different jobs:
T extends string | numbersays which types are allowed.= stringsays which allowed type to use when no type argument is provided.
A constraint does not automatically become the default. In Box<T extends string | number>, callers must provide T unless the declaration also gives T a default.
Ordering rules for type parameters
A required type parameter must come before any type parameter with a default. Once a parameter has a default, later parameters must also be optional or have defaults.
interface Result<TData, TError = Error> {
data?: TData;
error?: TError;
}
const success: Result<string> = {
data: "saved"
};
const failure: Result<string, { code: number }> = {
error: { code: 500 }
};Here, TData is required and comes first. TError has a default and comes second.
This ordering is invalid:
// interface Invalid<A = string, B> {}
// Error: a required type parameter cannot follow an optional type parameterThe rule exists because type arguments are supplied from left to right. TypeScript cannot omit the first argument while receiving only the second one. If a later parameter needs customization, give the earlier parameter a default too:
interface Config<TFormat = string, TOptions = Record<string, unknown>> {
format: TFormat;
options: TOptions;
}
type JsonConfig = Config<string, { pretty: boolean }>;Defaults on different declarations
Defaults can appear on interfaces, type aliases, classes, and functions.
interface ApiResponse<TData = unknown, TError = Error> {
data?: TData;
error?: TError;
}
type Pair<TLeft = string, TRight = number> = {
left: TLeft;
right: TRight;
};
class Store<TItem = string> {
constructor(public items: TItem[]) {}
}
function parse<T = unknown>(text: string): T {
return JSON.parse(text) as T;
}
const response: ApiResponse = {};
const pair: Pair = { left: "id", right: 1 };
const store = new Store(["a", "b"]);
const value = parse("42"); // value has type unknown
const count = parse<number>("42"); // count has type numberFor a class or interface, omitting a type argument uses the declaration’s default. For a function, TypeScript first tries to infer the type from the call. It uses the default only when inference has no candidate for that parameter.
Combining dependent constraints and defaults
A later default can refer to an earlier constrained type parameter. This pattern is useful when one type represents a complete object and another represents the data needed to create it.
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>;
const book = books.create({ title: "TypeScript Guide" });T must have an id: string property. The default for TCreate removes that property, so callers of Repository<Book> provide only { title: string }.
The default still follows the constraint rules. If a default refers to a type that does not meet its own constraint, the declaration is invalid.
Choosing between inference, defaults, and constraints
These three mechanisms play different roles:
| Mechanism | Purpose | Example |
|---|---|---|
| Inference | Derives a type from supplied values | `identity("hi")` infers `string` |
| Default | Supplies a type when no inference is available | `parse("42")` uses `unknown` |
| Constraint | Rejects types outside an allowed set | `Box<boolean>` is rejected |
The constraint is not a fallback value. For example, T extends string | number does not mean that TypeScript chooses string | number when it cannot infer T. Add an explicit default if that behavior is wanted.
When designing an API, put required parameters first, give common trailing parameters sensible defaults, and constrain defaults when the API depends on a particular shape.
Exercise
Why is type Cache<T extends object = string> = T invalid, and how could you fix it?
Show answer
It is invalid because string does not satisfy the object constraint. Use an object default, such as type Cache<T extends object = Record<string, unknown>> = T, or change the constraint if strings should be allowed.