The Analogy: The Assay Office and the Hallmark
A silversmith who wants to sell a batch of teapots as sterling cannot simply stamp them and put them in the window. By law the pieces go first to an assay office, an independent testing house that scrapes a little metal from each item and analyses it to see whether the silver really is as fine as the maker claims. Only when a piece passes does the office strike its hallmark into the metal, and only a hallmarked piece may be sold as sterling. The assay office is the boundary between the maker's word and the public's trust, and everything that crosses it is a claim until the office has tested it.
The maker's own stamp is only a claim, and the assay is the real check. A workshop can punch "925" into a teapot in seconds, and that punch asserts a purity of nine hundred and twenty-five parts per thousand, but the punch tests nothing; it is a label, not a measurement. The assay office ignores the maker's mark entirely and measures the metal for itself. In a program the network response is the teapot arriving with a "925" already stamped on it: response.json() hands you a value wearing a shape you would like it to have, and writing as User is believing the stamp. Typing the value as unknown and running it through a validator is sending it to the assay office to be measured before you trust it.
The office keeps one register of standards and works only from it, so the test and the definition of "sterling" can never drift apart. There is a single written standard for what sterling means, and the assayer tests against that one document rather than against a private memory of it. When a program derives its static type from the very same schema that performs the runtime check, it has that single register: change the standard in one place and both the test and the type it certifies move together, with no second copy to forget. A hallmark struck after a passing assay is the validated value, now safe to treat as sterling everywhere downstream because the one place that could have lied is the one place that measured.
The failure mode is trusting the maker's stamp instead of assaying, and it surfaces far from where the lie was told. A teapot stamped "925" that is really base metal plated thin will pass through every shop and every till without complaint, because everyone downstream trusts the stamp; the fraud is discovered only when someone finally melts it down, long after the sale. A value cast with as User behaves identically: the compiler believes the assertion and every caller reads user.name happily, and if the server actually sent null, an error object, or a record with name misspelled, nothing notices until the code touches the missing field at runtime. There is a second trap at the boundary itself: the courier delivers the box whatever is inside it, so fetch resolves even on a 404 or 500, and only a check of the response status catches a reply that was never the goods at all.
Syntax or Core Structure
Data crossing the network boundary should be typed unknown, not cast to your model. A type predicate then measures it, and only a value that passes is treated as the real type.
// src/boundary.ts
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) {
return false;
}
const v = value as Record<string, unknown>;
return typeof v.id === "number" && typeof v.name === "string";
}
const good: unknown = { id: 1, name: "ada" };
const bad: unknown = { id: 2 };
console.log(isUser(good));
console.log(isUser(bad));
if (isUser(good)) {
console.log(good.name);
}
Output:
true
false
ada
Both values are typed unknown, the honest type for anything that arrived from outside. isUser is the assay: it rejects non-objects and null, then checks each field's type. good has a numeric id and a string name, so it passes and prints true; bad lacks name, so typeof undefined is not "string" and it prints false. Inside the if, good is narrowed to User, so good.name is reachable and prints "ada". No as User cast was made anywhere; the type was earned by the check.
Technical Depth: The Status Check, a Hand Validator, and Lists
A reply arrives even when it is not the goods, so the status must be checked first; a type predicate with a handful of typeof checks is a complete validator; and a list is validated by checking every element.
The reply is delivered whatever is inside
A network call resolves for a 404 or a 500 just as it does for a 200, because the exchange succeeded even if the answer was an error. You must read the status before trusting the body.
// src/status.ts
interface Reply {
ok: boolean;
status: number;
body: unknown;
}
function readReply(reply: Reply): string {
if (!reply.ok) {
return "error " + reply.status;
}
return "ok " + reply.status;
}
const found: Reply = { ok: true, status: 200, body: { id: 1 } };
const missing: Reply = { ok: false, status: 404, body: { error: "not found" } };
console.log(readReply(found));
console.log(readReply(missing));
Output:
ok 200
error 404
Both replies arrived; the courier delivered the box in each case. found has ok: true and a status of 200, so readReply returns "ok 200". missing has ok: false and a status of 404, and its body is an error object, not the record you asked for, so the status check catches it and returns "error 404". Skipping the status check would treat that error object as the payload and read undefined fields off it later.
A hand-written validator is enough
A type predicate plus typeof checks validates an object completely, including a literal-union field checked by comparing against each allowed value.
// src/validate.ts
interface Account {
id: number;
name: string;
role: "admin" | "member";
}
function isAccount(value: unknown): value is Account {
if (typeof value !== "object" || value === null) {
return false;
}
const v = value as Record<string, unknown>;
return (
typeof v.id === "number" &&
typeof v.name === "string" &&
(v.role === "admin" || v.role === "member")
);
}
const rows: unknown[] = [
{ id: 1, name: "ada", role: "admin" },
{ id: 2, name: "grace", role: "member" },
{ id: 3, name: "bad", role: "root" },
];
for (const row of rows) {
console.log(isAccount(row));
}
Output:
true
true
false
The guard rejects non-objects and null first, then indexes through a single Record<string, unknown> cast that lets it read properties without claiming their types. The first two rows have a numeric id, a string name, and a role that is one of the two allowed literals, so they pass. The third has role: "root", which is neither "admin" nor "member", so the union check fails and it prints false. The typeof value !== "object" and separate value === null checks are both needed, because typeof null is itself "object".
Validating a whole list
An array is validated by narrowing with Array.isArray and then checking every element with the same predicate.
// src/list.ts
function isAccountArray(value: unknown): value is Account[] {
return Array.isArray(value) && value.every(isAccount);
}
const clean: unknown = [
{ id: 1, name: "ada", role: "admin" },
{ id: 2, name: "grace", role: "member" },
];
const dirty: unknown = [
{ id: 1, name: "ada", role: "admin" },
{ id: 2, name: "grace", role: "root" },
];
const empty: unknown = [];
console.log(isAccountArray(clean));
console.log(isAccountArray(dirty));
console.log(isAccountArray(empty));
Output:
true
false
true
isAccountArray first narrows unknown to an array with Array.isArray, then every runs isAccount on each element. clean has two valid accounts and passes; dirty has one bad role, so every short-circuits to false. The empty array passes with true, because every is vacuously true on an empty array; that is usually correct but worth knowing when an empty response should be treated as an error.
Hand-written guard against a schema library
| Aspect | Hand-written guard | Schema library |
|---|---|---|
| dependencies | none | one small package |
| source of truth | two, the type and the guard | one, the schema |
| error detail | whatever you write | field-level paths |
| best for | one or two endpoints | any real API surface |
A hand guard keeps the type and the check in two places that can drift, while a schema library derives the static type from the runtime schema so the two are one source of truth, the way the assay office tests against a single written standard rather than a remembered one.
Real World Example: A Client That Cannot Skip Validation
A typed client takes each reply and a parser, and there is no way to get a value out without supplying the parser, so validation is not optional. The generic load checks the status first, then hands the body to the parser, which either returns a typed value or throws. A batch of replies -- one good, one with a bad status, one good, one with the wrong shape -- is processed into a report.
// src/client.ts
type Parser<T> = (value: unknown) => T;
interface Reply {
ok: boolean;
status: number;
body: unknown;
}
class HttpError extends Error {
constructor(readonly status: number) {
super("HTTP " + status);
this.name = "HttpError";
}
}
interface Order {
ref: string;
amount: number;
}
function parseOrder(value: unknown): Order {
if (typeof value !== "object" || value === null) {
throw new Error("not an object");
}
const v = value as Record<string, unknown>;
if (typeof v.ref !== "string" || typeof v.amount !== "number") {
throw new Error("bad order shape");
}
return { ref: v.ref, amount: v.amount };
}
function load<T>(reply: Reply, parse: Parser<T>): T {
if (!reply.ok) {
throw new HttpError(reply.status);
}
return parse(reply.body);
}
function pad(text: string, width: number): string {
return text.padEnd(width);
}
const replies: Reply[] = [
{ ok: true, status: 200, body: { ref: "A1", amount: 120 } },
{ ok: false, status: 404, body: { error: "missing" } },
{ ok: true, status: 200, body: { ref: "C3", amount: 80 } },
{ ok: true, status: 200, body: { id: 4 } },
];
const rows: string[] = [];
let loaded = 0;
let total = 0;
for (let i = 0; i < replies.length; i++) {
try {
const order = load(replies[i], parseOrder);
loaded += 1;
total += order.amount;
rows.push(pad(String(i + 1), 5) + pad(order.ref, 6) + String(order.amount));
} catch (err) {
const note = (err as Error).name === "HttpError"
? "status " + (err as HttpError).status
: "bad body";
rows.push(pad(String(i + 1), 5) + pad("--", 6) + note);
}
}
const report = [
"replies: " + replies.length + ", loaded: " + loaded,
pad("N", 5) + pad("REF", 6) + "RESULT",
...rows,
"total: " + total,
];
console.log(report.join("\n"));
Output:
replies: 4, loaded: 2
N REF RESULT
1 A1 120
2 -- status 404
3 C3 80
4 -- bad body
total: 200
load takes a Reply and a Parser<T>, and there is no path that returns a value without running the parser, so no caller can accidentally trust an unchecked body. Reply one has ok: true and a body that parseOrder accepts, so it loads as order A1 for 120. Reply two has ok: false, so load throws an HttpError before the parser ever runs, and the row records "status 404". Reply three loads as C3 for 80. Reply four arrived with ok: true but its body is { id: 4 }, which parseOrder rejects for the missing fields, so the row records "bad body".
Trace the totals. Two of the four replies produced a valid order, so loaded is 2. Their amounts are 120 and 80, so total is 120 + 80, which is 200, printed in the footer. The two failures contribute nothing to the total, and their rows show why they were dropped rather than a figure.
The design has real limits worth naming. The sharpest flaw is how the catch tells the two failure kinds apart: it compares (err as Error).name against the string "HttpError", which is brittle, because any error whose name happened to be set to that string would be misread, and a rename of the class silently breaks the branch. The robust test is err instanceof HttpError, which checks the actual type rather than a label. The second limit is that the footer reports only the successful total and loaded count, with no aggregate of what failed; a batch that was mostly errors still prints a confident total, so a caller reading only the last line cannot see how much was dropped. Validating at the boundary keeps the bad data out, but a summary that counts only the survivors can still mislead about the health of the batch.
Common Mistakes
- Casting res.json() straight to your model. Writing
as Useris a promise you make to the compiler, not a check the runtime performs, so a malformed payload is believed and only breaks later when a missing field is read. Type the valueunknownand validate it.
- Forgetting to check the response status. A network call resolves for a 404 or 500 just as for a 200, so without a status check the error body is treated as the payload and its fields read as
undefined. Checkokor the status before trusting the body.
- Assuming the body always parses as JSON. An empty body or an HTML error page throws when parsed, so the parse itself can fail even after a successful exchange. Handle that failure rather than assuming a JSON object.
- Checking typeof value is "object" without the null test. Because
typeof nullis"object", a validator that omits the separatevalue === nullcheck will treatnullas a valid object and crash on the first field access.
- Validating deep in a component instead of at the boundary. Checking the shape where the data is finally used spreads the same check across many places and misses some. Validate once, in the function that owns the call, so the rest of the app can trust the type.
- Declaring a result as any or Promise of any. An
anyat the boundary disables checking for every caller downstream, silently reintroducing the very unsafety validation was meant to remove. Useunknownand narrow.
- Keeping the type and the guard as two separate sources. A hand-written interface and its guard drift apart as fields change; either keep them rigorously in step or derive the type from the schema so there is one source of truth.
- Distinguishing error kinds by a name string. Comparing an error's
.nameagainst a literal is brittle and breaks on a rename; useinstanceofto test the actual error type.
- Treating a no-content response as JSON. A 204 reply has no body to parse, so parsing it throws; branch on the status and return an empty result rather than parsing nothing.
Best Practices
- Type raw network data as unknown. Never
anyand never a direct cast to your model;unknownforces you to prove the shape before use, which is the check a cast skips.
- Validate at the boundary. Put the check in the one function that owns the call, so every caller downstream receives a value whose type has actually been verified.
- Derive the type from the runtime schema. When you use a schema library, let the static type come from the schema so the check and the type can never disagree, the way the assay office works from a single written standard.
- Always check the status and throw a typed error. Confirm the response succeeded before reading the body, and throw an error carrying the status so callers can tell a 404 from a 503.
- Make the parser a required argument. Design the request helper so a value cannot be obtained without supplying a parser, so validation is structurally impossible to forget.
- Distinguish errors with instanceof. Test error kinds by their type rather than a name string, so a class rename or a coincidental name does not misroute the handling.
- Log validation failures with the field path. Record which field failed and why, because a silent
nullor a swallowed mismatch costs hours to trace later.
- Summarise failures, not only successes. Report how many entries were dropped and why alongside the successful total, so a mostly-failed batch cannot hide behind a confident-looking figure.
Practice Exercises
- The honest cast. Take a function that does
return value as Producton anunknownand rewrite it with a hand-writtenisProductguard that throws on failure, then feed it a good and a malformed value.
- The status check. Add a status check and a custom
HttpErrorcarrying the status to a loader, then write a caller that usesinstanceofto show a different message for a 404 and a 500.
- The list validator. Write
isProductArrayusingArray.isArrayandevery, then show that a list with one bad element fails while an empty list passes, and decide whether the empty case should be an error for your endpoint.
- The tagged result. Rewrite the lesson's
loadso it returns an ok-or-error result instead of throwing, then build a report that summarises both the loaded total and a count of each failure kind.