Skip to content

Extending Typed APIs

The Course
•
15 min study

Add totalPages(books:readonly Book[]):number as a trusted-domain report. This function should not perform transport I/O or parse JSON. Decoders establish valid Book values; the report consumes those values without mutation.

Then decide where to expose the result. A formatter may display it from a ready state. If you add it to the state shape, update every constructor and the reducer so the field stays consistent with books. Storing redundant derived data creates another invariant; calculating it on demand may be simpler.

Write runtime tests for empty input, one zero-page book and several books. Write a negative compile test that rejects a page count encoded as text. Keep both layers: number types do not guarantee the sum implements the intended rule, while runtime tests do not maintain the entire caller-facing type surface.

A type-level change can guide edits, but it cannot decide which layer should own the feature. Prefer a small pure function when no lifecycle or dependency is needed.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
type Book = {
  readonly title: string;

  readonly pages: number;
};

function totalPages(books: readonly Book[]): number {
  let total = 0;

  for (const book of books) {
    total += book.pages;
  }

  return total;
}

console.log(
  totalPages([
    { title: "A", pages: 10 },
    { title: "B", pages: 20 }
  ])
);
console.log(totalPages([]));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
30
0

Keep trusted reporting outside the transport adapter

totalPages consumes trusted books, so it should not fetch, parse or silently repair records. Add a pure report at the layer that needs it and verify no input mutation. A numeric return type cannot prove that the loop sums the right field.

Storing the total alongside books adds a consistency rule to every state transition. Computing it when needed may be clearer for a small catalogue. Choose deliberately rather than assuming every derived display value deserves stored state.

Boundary or caseWhat to inspect
Empty booksZero without an absent-value fallback
Zero-page bookValid data contributes zero
Unequal page countsSum pages while preserving records and order

Add a negative caller with text pages and independent numeric fixtures. Then decide what exactness policy applies to very large totals; number annotations alone do not guarantee precision beyond safe integer bounds.

Your turn

Exercise

Extending Typed APIs: practice

totalPages was an addition beside the state machine. A real extension often changes the machine itself. This is the capstone's reducer with one change already made: the Action union has a new member, { type: "cancel"; request: number }. Click Check types and let the diagnostic tell you where the new action must be handled. Cancelling the request that is currently loading returns to idle; a cancel for any other request, or when nothing is loading, leaves the state unchanged. Print idle, loading 2 and ready 2 for the three scenarios at the bottom.

Find and fix the type errorTypeScript
type Book = { readonly id: string; readonly title: string; readonly pages: number };
type Result<T> =
  | { ok: true; value: T }
  | { ok: false; issue: { path: string; message: string } };

type State =
  | { tag: "idle" }
  | { tag: "loading"; request: number }
  | { tag: "ready"; request: number; books: readonly Book[] }
  | { tag: "error"; request: number; message: string };

type Action =
  | { type: "start"; request: number }
  | { type: "finish"; request: number; result: Result<readonly Book[]> }
  | { type: "cancel"; request: number };

function unreachable(value: never): never {
  throw new Error("Unhandled action");
}

function reduce(state: State, action: Action): State {
  switch (action.type) {
    case "start":
      return { tag: "loading", request: action.request };
    case "finish": {
      if (state.tag !== "loading" || state.request !== action.request) {
        return state;
      }
      if (action.result.ok) {
        return { tag: "ready", request: action.request, books: action.result.value };
      }
      return {
        tag: "error",
        request: action.request,
        message: `${action.result.issue.path}: ${action.result.issue.message}`
      };
    }
    default:
      return unreachable(action);
  }
}

function show(state: State): string {
  return state.tag === "idle" ? "idle" : `${state.tag} ${state.request}`;
}

let state = reduce({ tag: "idle" }, { type: "start", request: 1 });
console.log(show(reduce(state, { type: "cancel", request: 1 })));

state = reduce(state, { type: "start", request: 2 });
state = reduce(state, { type: "cancel", request: 1 });
console.log(show(state));

state = reduce(state, { type: "finish", request: 2, result: { ok: true, value: [] } });
console.log(show(reduce(state, { type: "cancel", request: 2 })));

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The diagnostic is on unreachable(action): the default branch is no longer impossible, because one Action member reaches it. That is the never check doing its job of listing unfinished work.

Hint 2: a first step

Add a case "cancel": before the default. Its first condition is the same stale-request test the finish case uses.

Show one solution
One possible solutionTypeScript
type Book = { readonly id: string; readonly title: string; readonly pages: number };
type Result<T> =
  | { ok: true; value: T }
  | { ok: false; issue: { path: string; message: string } };

type State =
  | { tag: "idle" }
  | { tag: "loading"; request: number }
  | { tag: "ready"; request: number; books: readonly Book[] }
  | { tag: "error"; request: number; message: string };

type Action =
  | { type: "start"; request: number }
  | { type: "finish"; request: number; result: Result<readonly Book[]> }
  | { type: "cancel"; request: number };

function unreachable(value: never): never {
  throw new Error("Unhandled action");
}

function reduce(state: State, action: Action): State {
  switch (action.type) {
    case "start":
      return { tag: "loading", request: action.request };
    case "finish": {
      if (state.tag !== "loading" || state.request !== action.request) {
        return state;
      }
      if (action.result.ok) {
        return { tag: "ready", request: action.request, books: action.result.value };
      }
      return {
        tag: "error",
        request: action.request,
        message: `${action.result.issue.path}: ${action.result.issue.message}`
      };
    }
    case "cancel":
      if (state.tag !== "loading" || state.request !== action.request) {
        return state;
      }
      return { tag: "idle" };
    default:
      return unreachable(action);
  }
}

function show(state: State): string {
  return state.tag === "idle" ? "idle" : `${state.tag} ${state.request}`;
}

let state = reduce({ tag: "idle" }, { type: "start", request: 1 });
console.log(show(reduce(state, { type: "cancel", request: 1 })));

state = reduce(state, { type: "start", request: 2 });
state = reduce(state, { type: "cancel", request: 1 });
console.log(show(state));

state = reduce(state, { type: "finish", request: 2, result: { ok: true, value: [] } });
console.log(show(reduce(state, { type: "cancel", request: 2 })));

Enable JavaScript to edit and type-check this example.

Text
idle
loading 2
ready 2

Adding the member made the default branch reachable, and the checker said exactly where: TS2345, { type: "cancel"; request: number } is not assignable to never. Once the case exists, action is never again in the default branch. What the checker could not tell you is the rule: returning { tag: "idle" } unconditionally would also compile, but then the stale cancel for request 1 would wipe out the loading request 2, and a late cancel would erase a finished result. The second and third lines are the evidence that the request-id check is there.

Change it and test it

Implement totalPages in the local project, export it from domain.ts and use it only after a ready-state check. Then add the cancel action there too and follow the same diagnostic through domain.ts; does any other file need to change? Explain whether storing totalPages in state is worth the extra consistency rule.

Was this article helpful?

Your response is saved on this device.