The complete catalogue boundary combines the week's ideas. Domain types describe Book and Result<T>. decodeBook validates and projects one record, arrayOf adds row paths, and decodeCatalogue rejects duplicate normalized ids. A typed transport remains Promise<unknown> until that boundary succeeds.
The loader catches transport rejection narrowly and returns a useful failure result. The reducer accepts finish only for the current loading request. Types enforce shape and narrowing; runtime checks enforce data rules and request identity. Readonly is shallow, so it communicates access intent without pretending the runtime is frozen.
Read the source in layers rather than memorizing its length; budget about fifteen minutes for reading and fifteen for the exercise. First inspect the two result variants, then one decoder, then the array wrapper, then the loader and reducer. Finally trace the short caller at the end. Every construct has appeared earlier in the course.
Download the modular project for real files, compile-only contracts and runtime tests. Its transport is a local fixture, not an HTTP request. It demonstrates stale-result rejection, not cancellation or a UI. Top-level await keeps this combined editor program alive until its caller completes.
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.
type Issue = {
readonly path: string;
readonly message: string;
};
type Result<T> =
| {
ok: true;
value: T;
}
| {
ok: false;
issue: Issue;
};
type Decoder<T> = (value: unknown) => Result<T>;
type Book = {
readonly id: string;
readonly title: string;
readonly pages: number;
};
const decodeBook: Decoder<Book> = value => {
if (typeof value !== "object" || value === null) {
return { ok: false, issue: { path: "book", message: "Expected a record" } };
}
if (
!("id" in value) ||
typeof value.id !== "string" ||
value.id.trim() === ""
) {
return {
ok: false,
issue: { path: "id", message: "Expected nonblank text" }
};
}
if (
!("title" in value) ||
typeof value.title !== "string" ||
value.title.trim() === ""
) {
return {
ok: false,
issue: { path: "title", message: "Expected nonblank text" }
};
}
if (
!("pages" in value) ||
typeof value.pages !== "number" ||
!Number.isFinite(value.pages) ||
!Number.isInteger(value.pages) ||
value.pages < 0
) {
return {
ok: false,
issue: { path: "pages", message: "Expected a nonnegative integer" }
};
}
return {
ok: true,
value: {
id: value.id.trim(),
title: value.title.trim(),
pages: value.pages
}
};
};
function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
return value => {
if (!Array.isArray(value)) {
return {
ok: false,
issue: { path: "list", message: "Expected an array" }
};
}
const output: T[] = [];
for (const [index, element] of value.entries()) {
const item: unknown = element;
const result = decode(item);
if (!result.ok) {
return {
ok: false,
issue: {
path: `${index}.${result.issue.path}`,
message: result.issue.message
}
};
}
output.push(result.value);
}
return { ok: true, value: output };
};
}
const decodeCatalogue: Decoder<readonly Book[]> = value => {
const result = arrayOf(decodeBook)(value);
if (!result.ok) {
return result;
}
const ids = new Set<string>();
for (const [index, book] of result.value.entries()) {
if (ids.has(book.id)) {
return {
ok: false,
issue: { path: `${index}.id`, message: "Duplicate id" }
};
}
ids.add(book.id);
}
return result;
};
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[]>;
};
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 unreachable(value: never): never {
throw new Error("Unhandled action");
}
type Transport = () => Promise<unknown>;
function createLoader(
transport: Transport
): () => Promise<Result<readonly Book[]>> {
return async () => {
let value: unknown;
try {
value = await transport();
} catch (error) {
return {
ok: false,
issue: {
path: "transport",
message: error instanceof Error ? error.message : "Request failed"
}
};
}
return decodeCatalogue(value);
};
}
const load = createLoader(async () => [
{ id: "b1", title: " Types ", pages: 120 }
]);
let state = reduce({ tag: "idle" }, { type: "start", request: 1 });
state = reduce(state, { type: "finish", request: 1, result: await load() });
if (state.tag === "ready") {
console.log(state.books.map(book => book.title).join(","));
}Enable JavaScript to edit and type-check this example.
Check your prediction
TypesTrace a request through three independent contracts
The transport supplies unknown because arrival is not validation. createLoader awaits it, converts transport rejection, then calls decodeCatalogue outside that catch. The decoder constructs trusted rows and checks normalized identities across the list. A successful decoded list still needs request ownership before it becomes current state: good data can belong to an old request.
| Boundary or case | What to inspect |
|---|---|
| Transport | Separate an unavailable service from successful malformed data |
| Catalogue | Return normalized all-or-error records and useful issue paths |
| State | Apply current loading completion and preserve exact state for stale work |
Trace an invalid second row to its prefixed path, then trace an old valid result while newer work is held. These cases protect different boundaries. Do not describe HTTP success or a typed finish action as proof that a state update should occur.
Your turn
Capstone: Typed Catalogue: practice
The workspace holds the listing above without its caller. Exercise the integrated code with three new scenarios, predicting each printed line before you run:
- A transport that rejects with
new Error("offline"), for request 1. - A transport that succeeds but whose second row has -5 pages, for request 2.
- A stale failure: start request 3, let its transport fail, start request 4 before finishing 3, then finish 3 with the failure and finally finish 4 with a good transport returning " Types ".
Write a show(state) that switches on all four state tags (titles joined by commas for ready, error message for error, loading N for loading), and print the state after each finish: four lines in all.
type Issue = {
readonly path: string;
readonly message: string;
};
type Result<T> =
| {
ok: true;
value: T;
}
| {
ok: false;
issue: Issue;
};
type Decoder<T> = (value: unknown) => Result<T>;
type Book = {
readonly id: string;
readonly title: string;
readonly pages: number;
};
const decodeBook: Decoder<Book> = value => {
if (typeof value !== "object" || value === null) {
return { ok: false, issue: { path: "book", message: "Expected a record" } };
}
if (
!("id" in value) ||
typeof value.id !== "string" ||
value.id.trim() === ""
) {
return {
ok: false,
issue: { path: "id", message: "Expected nonblank text" }
};
}
if (
!("title" in value) ||
typeof value.title !== "string" ||
value.title.trim() === ""
) {
return {
ok: false,
issue: { path: "title", message: "Expected nonblank text" }
};
}
if (
!("pages" in value) ||
typeof value.pages !== "number" ||
!Number.isFinite(value.pages) ||
!Number.isInteger(value.pages) ||
value.pages < 0
) {
return {
ok: false,
issue: { path: "pages", message: "Expected a nonnegative integer" }
};
}
return {
ok: true,
value: {
id: value.id.trim(),
title: value.title.trim(),
pages: value.pages
}
};
};
function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
return value => {
if (!Array.isArray(value)) {
return {
ok: false,
issue: { path: "list", message: "Expected an array" }
};
}
const output: T[] = [];
for (const [index, element] of value.entries()) {
const item: unknown = element;
const result = decode(item);
if (!result.ok) {
return {
ok: false,
issue: {
path: `${index}.${result.issue.path}`,
message: result.issue.message
}
};
}
output.push(result.value);
}
return { ok: true, value: output };
};
}
const decodeCatalogue: Decoder<readonly Book[]> = value => {
const result = arrayOf(decodeBook)(value);
if (!result.ok) {
return result;
}
const ids = new Set<string>();
for (const [index, book] of result.value.entries()) {
if (ids.has(book.id)) {
return {
ok: false,
issue: { path: `${index}.id`, message: "Duplicate id" }
};
}
ids.add(book.id);
}
return result;
};
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[]>;
};
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 unreachable(value: never): never {
throw new Error("Unhandled action");
}
type Transport = () => Promise<unknown>;
function createLoader(
transport: Transport
): () => Promise<Result<readonly Book[]>> {
return async () => {
let value: unknown;
try {
value = await transport();
} catch (error) {
return {
ok: false,
issue: {
path: "transport",
message: error instanceof Error ? error.message : "Request failed"
}
};
}
return decodeCatalogue(value);
};
}
// Add show(state), three transports and the three scenarios here.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
Each scenario is aimed at a different layer: the loader's catch, the decoder's row paths, and the reducer's request-id rule. Predict which layer decides each line.
Hint 2: a first step
Make each transport with createLoader(async () => ...). For scenario 3, await the failing loader's result into a variable first, then dispatch start 4, then dispatch finish 3 with that saved result.
Show one solution
type Issue = {
readonly path: string;
readonly message: string;
};
type Result<T> =
| {
ok: true;
value: T;
}
| {
ok: false;
issue: Issue;
};
type Decoder<T> = (value: unknown) => Result<T>;
type Book = {
readonly id: string;
readonly title: string;
readonly pages: number;
};
const decodeBook: Decoder<Book> = value => {
if (typeof value !== "object" || value === null) {
return { ok: false, issue: { path: "book", message: "Expected a record" } };
}
if (
!("id" in value) ||
typeof value.id !== "string" ||
value.id.trim() === ""
) {
return {
ok: false,
issue: { path: "id", message: "Expected nonblank text" }
};
}
if (
!("title" in value) ||
typeof value.title !== "string" ||
value.title.trim() === ""
) {
return {
ok: false,
issue: { path: "title", message: "Expected nonblank text" }
};
}
if (
!("pages" in value) ||
typeof value.pages !== "number" ||
!Number.isFinite(value.pages) ||
!Number.isInteger(value.pages) ||
value.pages < 0
) {
return {
ok: false,
issue: { path: "pages", message: "Expected a nonnegative integer" }
};
}
return {
ok: true,
value: {
id: value.id.trim(),
title: value.title.trim(),
pages: value.pages
}
};
};
function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
return value => {
if (!Array.isArray(value)) {
return {
ok: false,
issue: { path: "list", message: "Expected an array" }
};
}
const output: T[] = [];
for (const [index, element] of value.entries()) {
const item: unknown = element;
const result = decode(item);
if (!result.ok) {
return {
ok: false,
issue: {
path: `${index}.${result.issue.path}`,
message: result.issue.message
}
};
}
output.push(result.value);
}
return { ok: true, value: output };
};
}
const decodeCatalogue: Decoder<readonly Book[]> = value => {
const result = arrayOf(decodeBook)(value);
if (!result.ok) {
return result;
}
const ids = new Set<string>();
for (const [index, book] of result.value.entries()) {
if (ids.has(book.id)) {
return {
ok: false,
issue: { path: `${index}.id`, message: "Duplicate id" }
};
}
ids.add(book.id);
}
return result;
};
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[]>;
};
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 unreachable(value: never): never {
throw new Error("Unhandled action");
}
type Transport = () => Promise<unknown>;
function createLoader(
transport: Transport
): () => Promise<Result<readonly Book[]>> {
return async () => {
let value: unknown;
try {
value = await transport();
} catch (error) {
return {
ok: false,
issue: {
path: "transport",
message: error instanceof Error ? error.message : "Request failed"
}
};
}
return decodeCatalogue(value);
};
}
function show(state: State): string {
switch (state.tag) {
case "idle":
return "idle";
case "loading":
return `loading ${state.request}`;
case "ready":
return state.books.map(book => book.title).join(",");
case "error":
return `error ${state.message}`;
}
}
const good = createLoader(async () => [{ id: "b1", title: " Types ", pages: 120 }]);
const offline = createLoader(async () => {
throw new Error("offline");
});
const badRow = createLoader(async () => [
{ id: "b1", title: "Types", pages: 1 },
{ id: "b2", title: "API", pages: -5 }
]);
// 1. Transport rejects.
let state = reduce({ tag: "idle" }, { type: "start", request: 1 });
state = reduce(state, { type: "finish", request: 1, result: await offline() });
console.log(show(state));
// 2. Successful transport, invalid second row.
state = reduce(state, { type: "start", request: 2 });
state = reduce(state, { type: "finish", request: 2, result: await badRow() });
console.log(show(state));
// 3. Stale failure: request 3 fails late, after request 4 has started.
state = reduce(state, { type: "start", request: 3 });
const staleFailure = await offline();
state = reduce(state, { type: "start", request: 4 });
state = reduce(state, { type: "finish", request: 3, result: staleFailure });
console.log(show(state));
state = reduce(state, { type: "finish", request: 4, result: await good() });
console.log(show(state));Enable JavaScript to edit and type-check this example.
error transport: offline
error 1.pages: Expected a nonnegative integer
loading 4
TypesThe first line comes from the loader: its catch turns the rejection into a Result failure at path transport, and the reducer stores it as an error. The second comes from the decoder: the transport succeeded, but arrayOf reports the bad row as 1.pages, so the whole list is rejected. The third is the reducer's request-id rule: finish 3 arrives while 4 is loading, so the failure is ignored and the state stays loading 4; the fourth shows request 4 still completes normally. The checker made show handle all four tags (remove a case and the function no longer returns a string on every path), but every one of these outcomes is runtime behavior that only the scenarios show.
Change it and test it
Run the full example with a bad page count, blank title, duplicate normalized id and rejected transport. Trace which layer rejects each. Explain why the formatter should not be handed unvalidated unknown data under a Book[] assertion.
Completion is saved in this browser only. It does not measure mastery.