Sub topic 11
Designing Reusable APIs with Constraints and Defaults
This chapter assumes you know basic TypeScript types, interfaces, type aliases, union types, and generic functions. Familiarity with keyof and indexed access types such as T[K] is helpful.
Generic constraints and default type parameters solve different API problems:
- A constraint limits which types are valid and tells the function what members it may safely use.
- A default supplies a type when the caller does not provide one.
- Together, they can make an API safe for unusual cases and simple for common cases.
Start with the required invariant
Suppose every stored record must have a string id. Express that requirement on the main type parameter:
interface Entity {
id: string;
}
interface Repository<
T extends Entity,
TCreate = Omit<T, "id">
> {
create(input: TCreate): T;
findById(id: string): T | undefined;
}T extends Entity means that T must contain an id: string property. The repository can therefore expose operations that depend on that property.
TCreate describes the input needed to create a record. Its default removes id from T, because the repository may generate the identifier itself.
A caller can use the convenient default:
interface Book extends Entity {
title: string;
author: string;
}
declare const books: Repository<Book>;
const book = books.create({
title: "Dune",
author: "Frank Herbert"
});
// book has type BookThe same API remains flexible when creation needs a different shape:
interface BookDraft {
title: string;
author: string;
temporaryId: number;
}
declare const draftBooks: Repository<Book, BookDraft>;The default handles the normal case. The second type argument supports a deliberate variation.
Design defaults from the constrained type
A useful default often derives from another type parameter. This keeps related types synchronized:
type WithoutId<T extends { id: string }> = Omit<T, "id">;
interface Store<
T extends { id: string },
TInput = WithoutId<T>
> {
save(input: TInput): T;
}If T changes, the default input changes with it. You do not need to repeat the entity’s fields in the API declaration.
Keep the default narrow enough to be useful. unknown is a safe general default, but it may force callers to perform checks before using a value. A computed default such as Omit<T, "id"> often gives a better experience because it preserves known structure.
Use constraints to connect parameters
Constraints can express relationships between parameters, not only requirements on one parameter. A key-value API is a common example:
function updateField<
T extends object,
K extends keyof T
>(object: T, key: K, value: T[K]): T {
return { ...object, [key]: value };
}
const user = { id: 1, name: "Ada", active: true };
const updated = updateField(user, "active", false);
// updateField(user, "active", "yes"); // Error
// updateField(user, "email", "[email protected]"); // ErrorK extends keyof T restricts the key to properties that actually exist on T. The indexed access type T[K] then requires a value compatible with the selected property.
This relationship is usually better than accepting string for the key and unknown for the value. The latter compiles more calls but moves errors to runtime.
Choose defaults that preserve easy calls
A default should make the common call short without hiding an important decision. Consider an API response:
interface ApiResponse<
TData = unknown,
TError = Error
> {
data?: TData;
error?: TError;
}
const response: ApiResponse<string> = {
data: "ready"
};
const failed: ApiResponse<string, { code: number }> = {
error: { code: 503 }
};The first type argument can be supplied while the second keeps its default. This works because defaulted parameters are trailing.
| Declaration | Valid? | Reason |
|---|---|---|
| `ApiResponse` | Yes | Both parameters use defaults |
| `ApiResponse<string>` | Yes | `TError` uses its default |
| `ApiResponse<string, CustomError>` | Yes | Both parameters are explicit |
| `ApiResponse<, CustomError>` | No | Type arguments cannot skip the first parameter |
Required type parameters must come before parameters with defaults. A default must also satisfy its constraint:
type Page<T extends string | number = string> = {
value: T;
};
// type Bad<T extends string = number> = T; // ErrorUnderstand inference before adding defaults
For a generic function, TypeScript first uses information from the arguments to infer a type. If inference finds a type, that inferred type normally wins over the default. The default applies when no inference candidate exists.
function decode<T = unknown>(text: string): T {
return JSON.parse(text) as T;
}
const a = decode("42"); // unknown: no T appears in an input
const b = decode<number>("42"); // number: explicitly selectedThe assertion inside decode does not validate JSON at runtime. The default only describes the static type. If the function cannot prove the result, unknown is safer than any.
A practical design checklist
When combining constraints and defaults:
- Put the invariant on the main type parameter with
extends. - Derive a default from that parameter when the types are naturally related.
- Put required parameters before defaulted parameters.
- Make defaults match the most common use, not every possible use.
- Use dependent constraints such as
K extends keyof Twhen arguments must agree. - Check whether inference already provides the type before relying on a default.
- Avoid returning a fabricated value as
T; a value matching the constraint may still lack fields required by a specificT.
Exercise
In Repository<T extends { id: string }, TCreate = Omit<T, "id">>, what happens when a caller supplies Repository<Book>?
Show answer
T becomes Book, and TCreate defaults to Omit<Book, "id">, so creation requires Book's fields except id.