TypeScriptTeams

Designing APIs that are hard to misuse

Good names, fewer booleans and types that make wrong calls fail to compile. Notes from reviewing a few hundred pull requests against a shared library.

Alex Rivera

· 8 min read

Cable-stayed bridge cables seen from below

One boolean is fine, three are a bug

A call like send(message, true, false, true) can't be reviewed: nobody remembers what the third flag means. Booleans also combine into states that make no sense, like loading and error both true.

ts
// Before: 8 combinations, 3 of them validtype Props = { loading: boolean; error: boolean; empty: boolean };// After: exactly the states that existtype Props = { status: "loading" | "error" | "empty" | "ready" };

Options objects over positions

Past two arguments, take an object. Callers read like documentation, new options don't break old calls, and defaults live in one place.

ts
retry(fetchUser, { attempts: 3, backoff: "exponential" });

Make wrong calls fail to compile

Two ids that are both strings will be swapped one day. A brand costs nothing at runtime and turns that swap into a type error.

ts
type UserId = string & { readonly brand: "UserId" };type TeamId = string & { readonly brand: "TeamId" };declare function addMember(team: TeamId, user: UserId): Promise<void>;addMember(userId, teamId); // error: arguments are swapped

Errors that say what to do

An error message is part of the API. Say what was expected, what arrived, and the next step: Expected a TeamId, got "u_123" (a UserId). Did you swap the arguments? saves a support thread.

Keep reading