A function can have a perfect Decoder<Book> signature and still accept negative pages or duplicate ids. The compiler checks the implementation's declared relationships, not the complete truth of its validation algorithm.
Choose tests by boundaries: each required field missing independently, wrong primitive types, blank normalized text, zero, negative and fractional counts, NaN and Infinity, and normalized duplicate ids. For a whole-list decoder, assert that a bad second row rejects the list and reports its index.
Use a small assertion helper in the browser, or Node's assert module in the downloaded project. A useful helper compares an actual value with an expected one and, on failure, throws a message that names the case and shows both values; throw new Error("Assertion failed") tells you something broke but not what. Count the cases that actually ran instead of printing a hard-coded total, which can silently drift from the real number. The example below shows both habits, including what a failure looks like.
Keep a deliberate mutation: remove one guard and confirm a test fails while the source still compiles. That distinguishes behavioral evidence from a syntax or typing failure.
Also check projection and nonmutation. A successful decode should return only modeled fields and leave the source unchanged. Do not make test fixtures so friendly that they never exercise the contract's difficult parts.
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.
function assertEqual<T>(actual: T, expected: T, label: string): void {
if (actual !== expected) {
throw new Error(`${label}: expected ${String(expected)}, got ${String(actual)}`);
}
}
let passed = 0;
function check<T>(label: string, actual: T, expected: T): void {
assertEqual(actual, expected, label);
passed += 1;
}
check("trim", " Types ".trim(), "Types");
check("zero is a number", typeof 0, "number");
try {
check("deliberately wrong", 1 + 1, 3);
} catch (error) {
console.log(error instanceof Error ? error.message : String(error));
}
console.log(`${passed} cases passed`);Enable JavaScript to edit and type-check this example.
Check your prediction
deliberately wrong: expected 3, got 2
2 cases passedTarget each domain rule with an independent fixture
A type-correct decoder can still accept the wrong data. Choose fixtures that distinguish the individual rules: missing fields, wrong primitives, blanks, negative counts, fractions and valid zero. A single malformed object may trigger only its first failure and leave other rules untested.
Check normalized output and source preservation on success, not only rejection on bad data. Otherwise a decoder that always rejects could pass a negative-only suite. Keep the expected answer independent of the implementation expression.
function valid(value: unknown): boolean {
return (
typeof value === "number" &&
Number.isFinite(value) &&
Number.isInteger(value) &&
value >= 0
);
}
for (const value of [0, 1, -1, 1.5, "0", Infinity]) {
console.log(valid(value));
}Enable JavaScript to edit and type-check this example.
Check your prediction
true
true
false
false
false
falseEach case isolates a different reason. Zero and one also prove the predicate accepts ordinary valid inputs instead of rejecting everything.
const source = { title: " Types ", privateNote: true };
function clean(value: { title: string }): { title: string } {
return { title: value.title.trim() };
}
const result = clean(source);
if (
result.title !== "Types" ||
source.title !== " Types " ||
"privateNote" in result
) {
throw new Error("Boundary defect");
}
console.log("normalization, projection and input checked");Enable JavaScript to edit and type-check this example.
Check your prediction
normalization, projection and input checkedA smaller return annotation does not prove any of these runtime properties. The assertions protect actual behavior at the boundary.
Try the rule on new inputs
Remove one predicate clause at a time and identify a fixture that fails. Restore it before the next mutation. Add a bad second row to verify error paths include the correct index.
Your turn
Runtime Boundary Tests: practice
The workspace contains Day 4's composed decodeBook and arrayOf. Test them through their public Result, not a boolean: write an assertEqual(actual, expected, label) helper and a table of cases, each with a label, an input and the expected issue path (or undefined for success). Cover valid zero pages, a missing id, a blank title, fractional pages and a non-object (path ""). Then add two cases outside the table: a list whose second row has -1 pages must report 1.pages, and a padded title must come back trimmed. Count the cases as they pass and print 7 cases passed. Finally change count's value >= 0 to value >= 1 and check that the failure message names the broken case.
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 };
};
}
// Write assertEqual, a table of cases, and the two extra cases here.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
Comparing the issue path, not just ok, is what makes each case specific: a decoder that rejects a book for the wrong field would still say ok: false. Mapping a success to undefined lets one comparison cover both outcomes.
Hint 2: a first step
Write assertEqual as a generic function of (actual: T, expected: T, label: string) that throws an Error containing the label and both values. Then declare a Case type with path: string | undefined.
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 assertEqual<T>(actual: T, expected: T, label: string): void {
if (actual !== expected) {
throw new Error(`${label}: expected ${String(expected)}, got ${String(actual)}`);
}
}
// path undefined means "expect success".
type Case = { label: string; input: unknown; path: string | undefined };
const cases: Case[] = [
{ label: "valid zero pages", input: { id: "b1", title: "Types", pages: 0 }, path: undefined },
{ label: "missing id", input: { title: "Types", pages: 1 }, path: "id" },
{ label: "blank title", input: { id: "b1", title: " ", pages: 1 }, path: "title" },
{ label: "fractional pages", input: { id: "b1", title: "Types", pages: 1.5 }, path: "pages" },
{ label: "not an object", input: null, path: "" }
];
let passed = 0;
for (const testCase of cases) {
const result = decodeBook(testCase.input);
assertEqual(result.ok ? undefined : result.issue.path, testCase.path, testCase.label);
passed += 1;
}
const list = arrayOf(decodeBook)([
{ id: "b1", title: "Types", pages: 1 },
{ id: "b2", title: "Maps", pages: -1 }
]);
assertEqual(list.ok ? undefined : list.issue.path, "1.pages", "bad second row");
passed += 1;
const trimmed = decodeBook({ id: " b1 ", title: " Types ", pages: 3 });
assertEqual(trimmed.ok ? trimmed.value.title : undefined, "Types", "title is trimmed");
passed += 1;
console.log(`${passed} cases passed`);Enable JavaScript to edit and type-check this example.
7 cases passedThe checker made sure every case has the right shape and that result.issue is read only on failure. It has no opinion on whether decodeBook is right: that is what the seven observations are for. Each table row targets one rule and asserts where the decoder failed, so a mutation that breaks a different rule cannot hide behind ok: false. With count changed to value >= 1, the run stops with valid zero pages: expected undefined, got pages, naming the case and both values, and passed is never printed as 7. The list case checks the path composition that only arrayOf and field together produce.
Change it and test it
Make text return the untrimmed string and confirm exactly one case fails, with a useful message. Then add a case for every missing field and, in the download, a duplicate normalized id. Explain why readonly declarations do not prove that no runtime code elsewhere can mutate a shared record.
Completion is saved in this browser only. It does not measure mastery.