Sub topic 11
Designing Reusable APIs with Constraints and Defaults
This chapter combines the two features covered so far into design decisions for library and application code. It assumes you can write generic functions and interfaces. It also assumes you know extends constraints, keyof and T[K], the default syntax <T = string>, and the ordering rule that required parameters come before defaulted ones.
Two features, two jobs
A constraint and a default solve different problems. A constraint protects the implementation. A default protects the caller.
| Feature | Question it answers | Who benefits | Cost if misused |
|---|---|---|---|
| `T extends C` | What must the body be able to do with `T`? | The implementer, who gets to use members of `C` | Too tight rejects valid callers. Too loose forces casts inside the body. |
| `T = D` | What should `T` be when the caller says nothing? | The caller, who writes fewer type arguments | A careless default hides mistakes or silently weakens type safety. |
A parameter can have both. The constraint sets which types are allowed, and the default picks one of them for the case where nothing else is known.
A design checklist
Work through the questions below for each type parameter. They follow the order in which the decisions depend on each other.
Pattern 1: constrain to what the body needs
Name the smallest shape the body actually uses. Constraining to a concrete type like User works for one caller and blocks every other type that has the same members.
interface Identified {
id: string;
}
function indexById<T extends Identified>(items: readonly T[]): Map<string, T> {
return new Map(items.map((item) => [item.id, item] as const));
}
const lookup = indexById([
{ id: "a", size: 1 },
{ id: "b", size: 2 },
]);
// type: Map<string, { id: string; size: number }>Because T is the full element type, the result keeps size. A signature like (items: Identified[]): Map<string, Identified> would lose it. This is the main reason to use a generic here instead of a plain parameter type.
Keep the constraint minimal for the same reason. Each extra member you require rejects some callers who could have worked.
Pattern 2: derive defaults from constrained parameters
A default can refer to earlier parameters, including constrained ones. This works well when a second type is almost always a function of the first. The Repository example from earlier chapters fits this pattern, and here it has an implementation:
interface Entity {
id: string;
}
interface Repository<T extends Entity, TCreate = Omit<T, "id">> {
create(input: TCreate): T;
findById(id: string): T | undefined;
}
class InMemoryRepository<T extends Entity, TCreate = Omit<T, "id">>
implements Repository<T, TCreate>
{
private items = new Map<string, T>();
private nextId = 1;
constructor(private build: (input: TCreate, id: string) => T) {}
create(input: TCreate): T {
const item = this.build(input, String(this.nextId++));
this.items.set(item.id, item);
return item;
}
findById(id: string): T | undefined {
return this.items.get(id);
}
}
interface Book {
id: string;
title: string;
tags: string[];
}
// Common case: TCreate defaults to Omit<Book, "id">
const simple = new InMemoryRepository<Book>((input, id) => ({ ...input, id }));
simple.create({ title: "Dune", tags: [] });
// Override: callers send a draft where tags are optional
interface BookDraft {
title: string;
tags?: string[];
}
const drafts = new InMemoryRepository<Book, BookDraft>((input, id) => ({
id,
title: input.title,
tags: input.tags ?? [],
}));
drafts.create({ title: "Emma" });Two details matter here:
- The default
Omit<T, "id">is only valid becauseT extends Entityis declared first. The constraint onTis what guarantees"id"exists. - Writing
new InMemoryRepository<Book>(...)supplies only some type arguments. TypeScript does not infer the rest. It uses the defaults, soTCreateisOmit<Book, "id">and the callback parameters are contextually typed from it.
Pattern 3: default to the safe type
When a type cannot be recovered from the arguments, choose the default that forces callers to prove their assumptions. That default is nearly always unknown, not any.
interface Schema<T> {
parse(input: unknown): T;
}
async function fetchJson<T = unknown>(
url: string,
schema?: Schema<T>,
): Promise<T> {
const response = await fetch(url);
const body: unknown = await response.json();
return schema ? schema.parse(body) : (body as T);
}
const numberSchema: Schema<number> = {
parse(input) {
if (typeof input !== "number") throw new Error("expected a number");
return input;
},
};
async function main() {
const raw = await fetchJson("https://example.com/data.json");
// T has no candidates, so the default applies: unknown
const count = await fetchJson("https://example.com/count.json", numberSchema);
// T is inferred from the schema: number
const trusted = await fetchJson<{ id: number }>("https://example.com/item.json");
// explicit T: compiles, but nothing checks it at runtime
}This one function shows all three outcomes of the inference rule. An inferred type beats the default. The default applies when there is nothing to infer. An explicit argument overrides both.
The third call is a design weakness you should know about. An explicit T with no schema is an unchecked assertion. If that is unacceptable, use overloads so that a type argument is only accepted together with a schema.
Pattern 4: a loose constraint with a permissive default
Sometimes you want a fully typed mode and an untyped fallback. A class can offer both by pairing a loose constraint with a default that is also valid for it.
class Emitter<TEvents extends object = Record<string, unknown>> {
private handlers = new Map<keyof TEvents, Array<(payload: any) => void>>();
on<K extends keyof TEvents>(
event: K,
handler: (payload: TEvents[K]) => void,
): this {
const list = this.handlers.get(event) ?? [];
list.push(handler);
this.handlers.set(event, list);
return this;
}
emit<K extends keyof TEvents>(event: K, payload: TEvents[K]): void {
this.handlers.get(event)?.forEach((handler) => handler(payload));
}
}
type AppEvents = {
login: { user: string };
logout: undefined;
};
const bus = new Emitter<AppEvents>();
bus.on("login", (payload) => console.log(payload.user)); // payload: { user: string }
bus.emit("login", { user: "ada" });
// bus.emit("login", { user: 1 }); // Error: number is not assignable to string
// bus.emit("signup", undefined); // Error: "signup" is not a key of AppEvents
const loose = new Emitter(); // TEvents falls back to Record<string, unknown>
loose.on("anything", (payload) => console.log(payload)); // payload: unknownThe design choices are:
- The constraint is
object, notRecord<string, unknown>. An interface has no implicit index signature, so aninterface AppEventswould not be assignable toRecord<string, unknown>. Constraining toobjectaccepts both interfaces and type aliases. It is also enough forkeyofandTEvents[K]to work. - The default is
Record<string, unknown>. It satisfiesobject, and it letsnew Emitter()work with any string key. Payloads areunknown, so callers must narrow them before use. anyappears only in private storage. The public signatures stay precise. The one loose type is hidden where the class guarantees that handlers are only called with matching payloads.
Evolving the API without breaking callers
Defaults change how safely you can extend a generic type later:
- Adding a new type parameter with a default at the end is backward compatible. Existing uses such as
Emitter<AppEvents>keep compiling. - Adding a required parameter, or inserting any parameter before existing ones, breaks every existing reference that supplies type arguments positionally.
- Changing a default changes the meaning of every use that omits the argument. Treat it as a behavior change.
- Tightening a constraint can break callers whose types no longer satisfy it. Loosening one is generally safe.
For these reasons, order parameters by how often callers specify them. Put the one they almost always write first, and put the optional tuning knobs last.
Common failure modes
| Symptom | Cause | Fix |
|---|---|---|
| Callers must cast to use a returned value | Return type is the constraint type, not `T` | Return `T` or a type derived from `T` |
| Error that `{ id: number }` is not assignable to `T` | Constructing a new value of the constraint shape | Return the original `item`, or spread it into a value typed as `T` |
| A result is typed `unknown` and callers complain | Default applied because nothing could be inferred | Add a parameter that lets inference work, or document the default |
| A wrong type compiles without complaint | Default of `any`, or an explicit type argument that is only asserted | Default to `unknown`, and validate with a schema |
| Interface types rejected by a generic | Constraint is `Record<string, unknown>` | Constrain to `object` if you only need `keyof` |
| Error about required parameters after optional ones | Defaulted parameter placed before a required one | Reorder, or give the later parameter a default |
Exercises
Exercise
In the Emitter above, what is the type of payload in new Emitter().on("ready", (payload) => payload), and why?
Show answer
It is unknown. new Emitter() has no arguments to infer TEvents from, so the default Record<string, unknown> applies, and TEvents["ready"] is unknown.
Exercise
You are designing Cache<TKey, TValue>. Keys must be string or number, most callers use string keys, and the value type should be required. What declaration would you write, and what rule limits your choices?
Show answer
Put the required parameter first and give the key a default only if it can stay last, or give both parameters defaults. For example, class Cache<TValue, TKey extends string | number = string> is valid, because required parameters must precede defaulted ones. Writing Cache<TKey extends string | number = string, TValue> is an error. The default string also satisfies the constraint, as a default must.
Exercise
A teammate writes function create<T extends { id: number }>(): T { return { id: 0 }; }. Why does this fail, and how would you redesign it so callers get a T?
Show answer
The object { id: 0 } matches the constraint, but T could be a subtype with more required properties, so it is not assignable to T. Take the value from the caller, for example create<T extends { id: number }>(item: T): T, or accept a factory such as make: () => T.