Combine the whole day, plus Day 4's decoders, into one generic loader factory. createLoader(transport, decode) configures a loader once; each call load(signal) returns a Promise of the cancellation lesson's three-way Outcome<T>: ok with a value, cancelled, or error with a message.
- Port (lesson 2): the transport is injected:
(signal: AbortSignal) => Promise<unknown>. Its result is unknown until decoded. - Decoder (Day 4): any
Decoder<T>decides what a valid payload is, so one factory serves counts, titles or books, and T flows from the decoder into the Outcome. - Cancellation (lesson 3): an already-aborted signal returns cancelled without calling the transport; the signal is passed to the transport; if the signal is aborted when the transport settles (success or rejection), cancellation wins.
- A transport rejection on a live signal is error "Unavailable"; a decoder failure is error
path: message.
Do not use any or assertions, and keep the try block around the transport call only.
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 Loader = () => Promise<number>;
function createLoader(value: number): Loader {
return async () => value;
}
const load = createLoader(25);
console.log(await load());Enable JavaScript to edit and type-check this example.
Check your prediction
25Acceptance cases before you code
Predict the Outcome of each case before you code.
| Case to try | What your result should demonstrate |
|---|---|
| Transport resolves 0, count decoder | ok 0 (zero is a value) |
| Transport resolves " Types ", title decoder | ok Types: the same factory, a different T |
| Transport resolves "0", count decoder | error with the decoder's path and message |
| Transport rejects with the plain string "offline" | error Unavailable, without reading a message property from an unknown |
| Signal aborted before the call | cancelled, and the transport is never called |
| Transport aborts the signal, then resolves | cancelled, even though data arrived |
Delete the first signal.aborted check and only the call count notices (the outcome is still cancelled, thanks to the later check). Delete the check after the transport settles and only the last case notices. The types are identical in both broken versions.
Your turn
Checkpoint: Typed Loader: practice
Implement createLoader and a show function that prints ok value, error message or cancelled. Use a count decoder (path count, message Expected count) and a title decoder (nonblank, trimmed; path title, message Expected text). Run the six cases from the table, printing the transport call count after the pre-aborted case:
ok 0
ok Types
error count: Expected count
error Unavailable
cancelled 0
cancelled// Result, Decoder, Outcome and Transport types; createLoader; two decoders; six cases.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
There are three places where cancellation can be noticed (before the call, after a rejection, after a success) and two kinds of error (transport and decoding). Each one becomes a separate early return.
Hint 2: a first step
Write the signature first: one type parameter T, taken from decode: Decoder<T>, appearing again in the returned function's Promise<Outcome<T>>. The body returns async signal => { ... }.
Show one solution
type Result<T> =
| { ok: true; value: T }
| { ok: false; issue: { path: string; message: string } };
type Decoder<T> = (value: unknown) => Result<T>;
type Outcome<T> =
| { tag: "ok"; value: T }
| { tag: "cancelled" }
| { tag: "error"; message: string };
type Transport = (signal: AbortSignal) => Promise<unknown>;
function createLoader<T>(
transport: Transport,
decode: Decoder<T>
): (signal: AbortSignal) => Promise<Outcome<T>> {
return async signal => {
if (signal.aborted) {
return { tag: "cancelled" };
}
let raw: unknown;
try {
raw = await transport(signal);
} catch {
return signal.aborted
? { tag: "cancelled" }
: { tag: "error", message: "Unavailable" };
}
if (signal.aborted) {
return { tag: "cancelled" };
}
const result = decode(raw);
return result.ok
? { tag: "ok", value: result.value }
: { tag: "error", message: `${result.issue.path}: ${result.issue.message}` };
};
}
const count: Decoder<number> = value =>
typeof value === "number" && Number.isInteger(value) && value >= 0
? { ok: true, value }
: { ok: false, issue: { path: "count", message: "Expected count" } };
const title: Decoder<string> = value =>
typeof value === "string" && value.trim() !== ""
? { ok: true, value: value.trim() }
: { ok: false, issue: { path: "title", message: "Expected text" } };
function show<T>(outcome: Outcome<T>): string {
if (outcome.tag === "ok") {
return `ok ${outcome.value}`;
}
return outcome.tag === "error" ? `error ${outcome.message}` : "cancelled";
}
let calls = 0;
const live = new AbortController().signal;
console.log(show(await createLoader(async () => 0, count)(live)));
console.log(show(await createLoader(async () => " Types ", title)(live)));
console.log(show(await createLoader(async () => "0", count)(live)));
console.log(
show(
await createLoader(async () => {
throw "offline";
}, count)(live)
)
);
const early = new AbortController();
early.abort();
const counted = createLoader(async () => {
calls += 1;
return 1;
}, count);
console.log(show(await counted(early.signal)), calls);
const late = new AbortController();
const abortsDuringWork = createLoader(async () => {
late.abort();
return 5;
}, count);
console.log(show(await abortsDuringWork(late.signal)));Enable JavaScript to edit and type-check this example.
ok 0
ok Types
error count: Expected count
error Unavailable
cancelled 0
cancelledThe signature carries the design: T is inferred from the decoder, so createLoader(transport, title) returns loaders of Outcome<string>, and the transport's result stays unknown until decode(raw) has judged it. The checker also makes show narrow by tag before reading value or message. Everything about order and cancellation is runtime behavior the types cannot see: the 0 call count proves the transport was never started for an aborted signal, and the last case proves data that arrived after an abort is discarded. catch without a binding avoids reading anything from the thrown "offline".
Change it and test it
Count calls to prove creating a loader does not invoke the transport and each load invokes it once. Then pass Day 4's arrayOf(decodeBook) as the decoder: what is T now, and what does a bad second book report? A static Promise<Outcome<T>> signature cannot guarantee that your decoder checks every domain rule.
Completion is saved in this browser only. It does not measure mastery.