Build decodeBook, from unknown to a normalized Book (id, title, pages) or an Issue, out of small reusable decoders rather than one long if-chain. Start from the Array Decoders lesson's Result, Decoder, at, count, field and arrayOf (retype them or reuse your own). Then:
- Write one new leaf decoder,
text, that accepts a nonblank string and returns it trimmed. Like count, it reports an empty path. - Write decodeBook by running
field("id", text),field("title", text)andfield("pages", count)in that order, returning the first failure unchanged and building the Book only when all three succeed. Zero pages is valid; extra input properties are not copied; the source is not changed. - Use
arrayOf(decodeBook)on a list and check that a bad second row is reported as1.pages.
Field order is a public policy: a value failing several rules reports the first failed field. Because every piece adds its own part of the path, no function in your solution should build a path string by hand except at.
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.
const record: unknown = { id: " b1 ", title: " Types ", pages: 0 };
if (
typeof record === "object" &&
record !== null &&
"id" in record &&
typeof record.id === "string"
) {
console.log(record.id.trim());
}Enable JavaScript to edit and type-check this example.
Check your prediction
b1Acceptance cases before you code
Predict the report for each case before you code.
| Case to try | What your result should demonstrate |
|---|---|
| Zero pages with padded strings | Accept and normalize |
| Text pages or a missing required field | Reject at the relevant field path |
| Extra private input property | Do not copy it into success |
| A blank title | title: Expected text, with the path added by field, not by text |
| A list whose second row has fractional pages | 1.pages: arrayOf adds the index, field adds the name |
Try making text return the untrimmed string: everything still compiles, and only the normalization case notices. Try returning { ok: false, issue: id.issue } with a hand-written path instead of the failure itself: the list case shows whether you lost the field name.
Your turn
Checkpoint: Book Decoder: practice
Implement the brief. Print title: pages for a success and path: message for a failure, for: a padded valid book with zero pages and an extra private field; text pages; a blank title; and a two-row list whose second row has 2.5 pages. Then print whether the success contains private (false) and whether the source's title is still padded (true).
// Reuse the lesson's decoders, add text, then compose decodeBook.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
Each field(name, decoder) call is itself a decoder, already responsible for the object check and the path. decodeBook only sequences three of them and assembles the record.
Hint 2: a first step
Write text first, modeled on count. Then in decodeBook, call field("id", text)(value) and, if the result is not ok, return that result as it is; the failure member of any Result fits Result<Book>.
Show one solution
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;
function at(prefix: string, path: string): string {
return path === "" ? prefix : `${prefix}.${path}`;
}
const count: Decoder<number> = value =>
typeof value === "number" && Number.isInteger(value) && value >= 0
? { ok: true, value }
: { ok: false, issue: { path: "", message: "Expected count" } };
function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
return value => {
if (typeof value !== "object" || value === null) {
return { ok: false, issue: { path: "", message: "Expected object" } };
}
const raw: unknown = Reflect.get(value, name);
const result = decode(raw);
if (result.ok) {
return result;
}
return {
ok: false,
issue: { path: at(name, result.issue.path), message: result.issue.message }
};
};
}
const text: Decoder<string> = value =>
typeof value === "string" && value.trim() !== ""
? { ok: true, value: value.trim() }
: { ok: false, issue: { path: "", message: "Expected text" } };
type Book = {
readonly id: string;
readonly title: string;
readonly pages: number;
};
function decodeBook(value: unknown): Result<Book> {
const id = field("id", text)(value);
if (!id.ok) {
return id;
}
const title = field("title", text)(value);
if (!title.ok) {
return title;
}
const pages = field("pages", count)(value);
if (!pages.ok) {
return pages;
}
return {
ok: true,
value: { id: id.value, title: title.value, pages: pages.value }
};
}
function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
return value => {
if (!Array.isArray(value)) {
return { ok: false, issue: { path: "", message: "Expected 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: at(String(index), result.issue.path),
message: result.issue.message
}
};
}
output.push(result.value);
}
return { ok: true, value: output };
};
}
function report(result: Result<Book>): string {
return result.ok
? `${result.value.title}: ${result.value.pages}`
: `${result.issue.path}: ${result.issue.message}`;
}
const source = { id: " b1 ", title: " Types ", pages: 0, private: true };
const a = decodeBook(source);
console.log(report(a));
console.log(report(decodeBook({ id: "b2", title: "Types", pages: "10" })));
console.log(report(decodeBook({ id: "b3", title: " ", pages: 10 })));
const list = arrayOf(decodeBook)([source, { id: "b4", title: "Maps", pages: 2.5 }]);
console.log(list.ok ? "unexpected" : `${list.issue.path}: ${list.issue.message}`);
console.log(a.ok && "private" in a.value);
console.log(source.title === " Types ");Enable JavaScript to edit and type-check this example.
Types: 0
pages: Expected count
title: Expected text
1.pages: Expected count
false
trueEvery check now lives in exactly one small decoder: text owns "nonblank and trimmed", count owns "nonnegative integer", field owns "is an object, read this key, prefix this name", and arrayOf owns iteration and indexes. That is why the list failure reads 1.pages with no path code in decodeBook. The checker verifies the plumbing: if (!id.ok) return id; type-checks because a failure carries no value, and id.value is a string only after that line. It cannot verify the rules themselves, so the blank-title, text-pages and 2.5-pages cases are the evidence, and the last two lines show that construction copied only the modeled fields and left the source untouched.
Change it and test it
Write runtime assertions for every field boundary, including NaN and Infinity supplied directly. Then add an optional field: write optional(decode) that accepts undefined and otherwise defers to decode, and use it for a subtitle. Which of your existing pieces had to change? (Only decodeBook should.)
Completion is saved in this browser only. It does not measure mastery.