The Analogy: The Quarantine Bay at a Dockside Cold Store
A reefer container comes off a ship at four in the morning and its paperwork does not match its contents. The yard foreman has three places to put those pallets. He can wave them straight through the shutter into the chill hall as though they had been checked, and once they are stacked in with everything else nobody will ever ask again. He can put them in the quarantine bay: a fenced-off corner where a pallet may be moved, weighed, photographed and given a location, but where the shutter into the chill hall stays shut until an inspector opens a case and writes down what is actually inside. Or the pallet may turn out to be a load the store is not licensed to hold at all, in which case there is no bay for it, and the only correct action is to stop and refuse it.
The quarantine bay is slower and everybody hates it. Every pallet in it needs a person, a thermometer and five minutes before it can earn a location in the chill hall. What the bay buys is that the chill hall's stock record stays true: every pallet inside the shutter has been opened by somebody whose name is on the sheet. The cost is paid once, at the gate, by the yard crew, instead of being paid later by whoever finds a pallet of ice cream sitting at plus four degrees.
The third case deserves a moment. On the yard drawing there is a hatched rectangle marked "not licensed -- no storage", and no pallet has ever stood in it, because the licence does not permit one to. It is not wasted space; it is a proof. If the yard log ever shows stock in that rectangle, the routing rules that put it there are wrong, and the error is in the plan rather than in the goods. A bay that can never be occupied is exactly the thing that turns an impossible situation into a visible one.
The failure mode is the first route, and it is popular because at four in the morning it is the only one that keeps the yard moving. Nothing fails at the gate. The pallet is scanned, given a location, and from that moment the store's own records say it was received normally, which is a stronger claim than "nobody looked". Worse, it does not stay isolated: the next order picks cases from it onto a mixed pallet, that pallet goes out to three shops, and the fault surfaces a fortnight later as a customer complaint with no way back to which container it came from. The pallet did not become correct by being waved through; the only thing that changed is that the store lost the ability to find out.
Syntax or Core Structure
The three types are the three routes off the quay. any waves the value through: the compiler stops asking questions about it and stops asking questions about anything it touches. unknown accepts the value and holds it: you can store it, pass it, log it, but you cannot use it as anything in particular until you have proved what it is. never is the bay that can hold nothing, which makes it the type of an expression that does not produce a value at all. All three appear below, and every line of this file compiles under strict:
// src/wildcards.ts
const loose: any = "42";
const total: number = loose + 1;
console.log(total, typeof total);
const sealed: unknown = "42";
// const rejected: number = sealed; // error TS2322: 'unknown' is not assignable to 'number'
let parsed = 0;
if (typeof sealed === "string") {
parsed = Number(sealed) + 1;
}
console.log(parsed, typeof parsed);
function reject(reason: string): never {
throw new Error(reason);
}
function shelfWidth(label: string): number {
if (label === "narrow") return 60;
if (label === "wide") return 120;
return reject("no such shelf: " + label);
}
console.log(shelfWidth("narrow"), shelfWidth("wide"));
Output:
421 string
43 number
60 120
Read the first two lines of that output carefully, because they are the whole lesson. total is annotated number, the file compiles without a single complaint, and at runtime total holds the string 421 -- "42" + 1 is string concatenation, and any on the right-hand side means nobody checked. The unknown version of the same value cannot be assigned to number at all, so the only way forward was the typeof test, and after it Number(sealed) + 1 really is arithmetic and really is 43. The third line never prints a third figure for a bad label, because reject is declared to return never: it is a function the compiler knows cannot hand control back, which is why return reject(...) satisfies a signature that promises a number.
Technical Depth: The Top Type, the Bottom Type, and the Off Switch
Two of these three have a proper place in the type system. unknown is the top type: every type is assignable to it, and it is assignable to nothing but itself and any. never is the bottom type: nothing is assignable to it, and it is assignable to every type. any is not part of that ordering at all -- it is a switch that turns checking off in both directions, which is why it behaves like the top type and the bottom type at the same time.
What any actually switches off
| What you can do with the value | any | unknown | never |
|---|---|---|---|
Assign a string into it | yes | yes | no, nothing is assignable to it |
Assign it into a number | yes | no, error TS2322 | yes, it is assignable to everything |
| Read a property off it | yes, unchecked | no, error TS2571 until narrowed | no value can reach the expression |
| Call it as a function | yes, unchecked | no, error TS2571 | no value can reach the expression |
Use it in value + 1 | yes, unchecked | no, error TS18046 | no value can reach the expression |
Union it with string | the union collapses to any | the union collapses to unknown | the union stays string |
Intersect it with string | the result is any | the result is string | the result is never |
The row that causes real damage is the second one. any flows into typed variables silently, and once it has, the variable's annotation is a comment rather than a fact. It travels through function boundaries just as easily:
// src/leak.ts
const config: any = { retries: "3" };
function retriesFor(c: any): number {
return c.retries;
}
const n = retriesFor(config);
console.log(n + 2, typeof n);
console.log(Number.isInteger(n));
Output:
32 string
false
n is a number according to every tool in the project: the editor offers toFixed on it, a rename refactor treats it as numeric, and tsc is silent. At runtime it is the string 3, so n + 2 concatenates and Number.isInteger(n) is false. Note also that noImplicitAny does nothing here, because neither any is implicit -- somebody wrote both of them. The flag catches the parameter you forgot to annotate; only a review catches the one you annotated with any on purpose.
The five ways to open a sealed envelope
A value typed unknown is useless until it has been narrowed, and TypeScript recognises exactly five kinds of proof: typeof for primitives, instanceof for class instances, Array.isArray for arrays, the in operator for a property that may or may not be there, and a user-defined predicate of the form value is T for anything the first four cannot express. All five appear here:
// src/open.ts
function describe(value: unknown): string {
if (typeof value === "string") return "string of " + value.length;
if (typeof value === "number") return "number " + value.toFixed(1);
if (Array.isArray(value)) return "array of " + value.length;
if (value instanceof Date) return "date at epoch " + value.getTime();
if (typeof value === "object" && value !== null && "kg" in value) {
return "object with kg";
}
return "unopened";
}
console.log(describe("pallet"));
console.log(describe(48));
console.log(describe([1, 2, 3]));
console.log(describe(new Date(0)));
console.log(describe({ kg: 312.5 }));
console.log(describe(null));
Output:
string of 6
number 48.0
array of 3
date at epoch 0
object with kg
unopened
Three details in that function are worth naming. value.length is legal on line one only because typeof value === "string" came first; delete the test and the same expression is error TS18046. The value !== null clause is not decoration: typeof null is "object", so without it the last branch would accept null and any property test on it would throw at runtime. And the final return "unopened" exists because unknown has no fallback -- if you cannot prove what a value is, the only honest answer is to say so, which is precisely what the yard crew does when the paperwork does not match.
For shapes of your own, a predicate is the only tool that scales. function isPallet(v: unknown): v is Pallet tells the compiler "if this returns true, treat the argument as a Pallet from here on", and the compiler takes that entirely on trust: the body is ordinary code that you are responsible for getting right. A related form, function assertPallet(v: unknown): asserts v is Pallet, narrows the caller's variable instead of returning a boolean, and must throw when the claim is false.
never: the bay that cannot be occupied
never arrives from four places: a function that always throws, a function that never terminates, an impossible intersection such as string & number, and the end of a narrowing chain where every possibility has already been handled. The last one is the useful one, because it turns "we added a case and forgot to handle it" into a compile error:
// src/exhaustive.ts
type Zone = "chill" | "freeze" | "ambient";
function holdTemperature(zone: Zone): number {
switch (zone) {
case "chill": return 2;
case "freeze": return -18;
case "ambient": return 15;
default: {
const unreachable: never = zone;
return unreachable;
}
}
}
const zones: Zone[] = ["chill", "freeze", "ambient"];
for (const z of zones) {
console.log(z, holdTemperature(z));
}
Output:
chill 2
freeze -18
ambient 15
The default branch never runs, and that is the point. Inside it, all three members of Zone have been eliminated, so zone has type never and the assignment is legal. Add "dock" to Zone and leave the switch alone, and the compiler names the exact line and the exact member you forgot:
error TS2322: Type '"dock"' is not assignable to type 'never'.
Do not confuse never with void. A void function returns; it just has nothing worth handing back, and const x = doSomething() is legal with x typed void. A never function does not return at all, so any statement after a call to one is dead code. There is one subtlety worth knowing: TypeScript only uses that fact for control-flow analysis when the return type is written out explicitly. function reject(m: string): never narrows the code after a call to it; the same body with the annotation left off is inferred as void, and the compiler will then insist you handle a path that cannot happen.
Where any gets in without anybody typing it
Most of the any in a real codebase was never written down. It comes in through the library types at the edges of the program, which is exactly where the data is least trustworthy:
| Where it comes from | What you actually get | What to do instead |
|---|---|---|
JSON.parse(text) | any, no matter what the text contained | store the result in a variable annotated unknown |
await res.json() | any, straight from the DOM library types | pin it to unknown, then run a predicate over it |
localStorage.getItem(k) | string or null, then any once parsed | handle the null case, then treat the parse as unknown |
| an import with no type declarations | every export is implicitly any | write a rough .d.ts of your own for the parts you use |
catch (err) with the flag off | any, so err.message compiles and may be undefined | keep useUnknownInCatchVariables on and test err instanceof Error |
value as any | a hole you opened by hand | narrow properly, or confine the assertion to one adapter function |
Object.entries on an any object | any keys and any values | type the record first, so the values come out unknown |
| a generic call with nothing to infer from | unknown in current TypeScript, any in older code | pass the type argument explicitly |
The pattern in the right-hand column is always the same shape: put the value in the quarantine bay, then prove what it is. unknown at a boundary costs you one predicate and one error path. any at a boundary costs you nothing today and removes your ability to find out later, which is the trade the yard foreman made at four in the morning.
Real World Example: The Intake Sheet at the Cold Store
A manifest arrives as JSON and is parsed into memory, which means every row of it is any the moment JSON.parse returns. The program below does the one thing that matters at a boundary: it pins the parsed rows to unknown, proves each row is a Pallet before using it, and prints a reason for every row it refuses. Six rows go in, three come out fit for the chill hall, and the three rejections each name the field that failed:
// src/intake.ts
// checked with strict and noUncheckedIndexedAccess
type Zone = "chill" | "freeze" | "ambient";
type Pallet = { ref: string; zone: Zone; cases: number; kg: number };
// as if this had come back from JSON.parse: no types, no promises
const MANIFEST: unknown[] = [
{ ref: "P-1001", zone: "chill", cases: 48, kg: 312.5 },
{ ref: "P-1002", zone: "freeze", cases: 24, kg: 180 },
{ ref: "P-1003", zone: "tropical", cases: 12, kg: 96 },
{ ref: "P-1004", zone: "ambient", cases: 60, kg: 402.25 },
{ ref: 1005, zone: "chill", cases: 30, kg: 210 },
{ ref: "P-1006", zone: "freeze", cases: 18.5, kg: 140 },
];
function isZone(value: unknown): value is Zone {
return value === "chill" || value === "freeze" || value === "ambient";
}
function isPallet(value: unknown): value is Pallet {
if (typeof value !== "object" || value === null) return false;
const row = value as Record<string, unknown>;
return typeof row.ref === "string"
&& isZone(row.zone)
&& typeof row.cases === "number" && Number.isInteger(row.cases)
&& typeof row.kg === "number" && Number.isFinite(row.kg);
}
function faultOf(value: unknown): string {
if (typeof value !== "object" || value === null) return "not an object";
const row = value as Record<string, unknown>;
if (typeof row.ref !== "string") return "ref is not a string";
if (!isZone(row.zone)) return "zone " + JSON.stringify(row.zone) + " is not a zone";
if (typeof row.cases !== "number" || !Number.isInteger(row.cases)) {
return "cases is not a whole number";
}
return "kg is not a finite number";
}
function labelOf(value: unknown): string {
if (typeof value === "object" && value !== null) {
const row = value as Record<string, unknown>;
if (typeof row.ref === "string") return row.ref;
}
return "(no ref)";
}
function holdTemperature(zone: Zone): number {
switch (zone) {
case "chill": return 2;
case "freeze": return -18;
case "ambient": return 15;
default: {
const unreachable: never = zone;
return unreachable;
}
}
}
function pad(text: string, width: number): string {
return text + " ".repeat(Math.max(0, width - text.length));
}
function intake(rows: unknown[]): string {
const lines: string[] = [pad("REF", 10) + pad("ZONE", 10) + pad("CASES", 7)
+ pad("KG", 10) + "HOLD"];
const refused: string[] = [];
let cases = 0;
let kg = 0;
for (const row of rows) {
if (!isPallet(row)) {
refused.push("rejected: " + labelOf(row) + " (" + faultOf(row) + ")");
continue;
}
cases = cases + row.cases;
kg = kg + row.kg;
lines.push(pad(row.ref, 10) + pad(row.zone, 10) + pad(String(row.cases), 7)
+ pad(String(row.kg), 10) + holdTemperature(row.zone) + "C");
}
lines.push(pad("TOTAL", 10) + pad("", 10) + pad(String(cases), 7) + String(kg));
return lines.concat(refused).join("\n");
}
console.log(intake(MANIFEST));
Output:
REF ZONE CASES KG HOLD
P-1001 chill 48 312.5 2C
P-1002 freeze 24 180 -18C
P-1004 ambient 60 402.25 15C
TOTAL 132 894.75
rejected: P-1003 (zone "tropical" is not a zone)
rejected: (no ref) (ref is not a string)
rejected: P-1006 (cases is not a whole number)
Three pallets reach the chill hall, three are turned back at the gate with the field that failed written next to the reference, and the totals at the bottom describe only what was accepted: 132 cases and 894.75 kg. That last point is the one an auditor cares about. The sheet is not a summary of what arrived, it is a summary of what was proved, and the rejected rows are printed on the same sheet so that nobody has to go looking for them in a log.
The design rests on one annotation: const MANIFEST: unknown[]. Inside the loop, row is a sealed envelope -- row.cases will not compile, row.kg + 1 will not compile, and the only way past the compiler is isPallet(row). After that call returns true, row is a Pallet and every field is genuinely typed, which is why row.cases can be added to a number and row.zone can be handed to holdTemperature without a cast. Had the manifest been annotated Pallet[] instead -- which JSON.parse would have let you do without a murmur -- the three bad rows would have gone straight through: the totals would read 192.5 cases and 1340.75 kg, the HOLD column would say tropicalC, and the sheet would print six confident rows with no indication that anything had been wrong.
never does the other half of the work, quietly. The default branch of holdTemperature cannot run, because isZone has already ruled out everything except the three members of Zone, and the const unreachable: never = zone line exists only so that the compiler will object the day somebody licenses a fourth zone. That is a different kind of safety from the type guard: the guard protects the program from bad data at runtime, while the never assignment protects the program from its own authors at build time. Neither is optional, and neither replaces the other.
The limits are worth stating plainly, because two of them are the sort of thing that survives code review. First, isPallet and faultOf encode the same four rules twice, in the same order, with no mechanism tying them together; add a temperature field to Pallet and update only the guard, and a bad row is rejected with a reason that names the wrong field. Second, both functions reach the fields through value as Record<string, unknown>, an assertion sitting at the heart of the code whose whole job is to avoid assertions -- misspell row.cases as row.case and the file still compiles, the predicate still returns a boolean, and every row is silently refused. Third, Number.isFinite(row.kg) is a check that the value is a number, not that it is a weight: a pallet declared at -140 kg passes the gate and reduces the day's total. And nothing prints the row's position in the manifest, so (no ref) identifies a fault without identifying the row that caused it -- fine with six rows, useless with six thousand.
Common Mistakes
- Reaching for
anyto make an error go away: The error was information about a value you had misunderstood.anydeletes the message and keeps the misunderstanding, and becauseanyis assignable to everything, the consequence surfaces somewhere else entirely -- usually asundefined is not a functionin a file you did not touch. - Forgetting that the parse boundaries hand you
any:JSON.parse,await res.json(),evaland most untyped imports are all typedanyin the standard libraries. Annotating the receiving variable asunknowncosts one word and is the only thing standing between a bad payload and your whole program. - Using
aswhere a check belongs:data as Palletcompiles because you told the compiler to stop thinking, not because the data is a pallet. Assertions are for facts you can establish out of band; incoming data is never one of those facts. - Writing a predicate that does not check what it claims:
function isPallet(v: unknown): v is Pallet { return typeof v === "object"; }is worse than no guard at all, because now the lie is documented in a signature the rest of the codebase trusts. Every field the type promises must be tested in the body. - Hiding an assertion inside a generic helper:
function parse<T>(text: string): T { return JSON.parse(text); }looks typed and is not -- the caller picksTand nothing verifies it. It isas Twith extra steps, and it defeats every boundary check in the project. - Writing
catch (err: any)to get.message: That annotation switches offuseUnknownInCatchVariablesfor that block. Anything can be thrown in JavaScript, including strings and undefined, so testerr instanceof Errorand fall back toString(err). - Confusing
neverwithvoid: Avoidfunction returns and gives you nothing; aneverfunction does not return. Annotating a throwing helper asvoidmeans the compiler still believes the code after the call is reachable, and you lose the narrowing that made the helper worth writing. - Ending a switch with
default: throwinstead of theneverassignment: A throw is discovered by whoever runs that branch, which may be a customer.const unreachable: never = valueis discovered by whoever adds the new union member, which is the person who can still fix it cheaply. - Expecting
unknownto survive a union, or reading{}as "an empty object": Union anything withunknownand the whole union collapses tounknown, so anunknownmember is doing nothing you intended. And{}does not mean an object with no properties, it means anything exceptnullandundefined-- a parameter typed{}accepts42and"text"without complaint. Writeobjectwhen you mean some object, andunknownwhen you mean you do not know yet.
Best Practices
- Annotate the boundary, not the destination: Write
const data: unknown = JSON.parse(text)on the line where the value arrives. Annotating three functions downstream is too late, because theanyhas already been assigned into typed variables on the way there. - One predicate per shape, and test it like code: A guard is ordinary logic with an extraordinary amount of trust placed in it, so give it unit tests: one valid row, and one row per field with that field wrong. A guard nobody tested is an assertion with better manners.
- Let one declaration produce both the check and the message: The duplication between
isPalletandfaultOfis what schema libraries exist to remove -- a single schema yields the predicate, the inferred type and the field-level error. Hand-written guards are fine for two or three shapes and a liability at twenty. - Confine
anyto one adapter and name it honestly: If a third-party library forces your hand, put theanyin one small function, validate on the way out, and return a real type. Call the variableunsafeRowrather thandataso the next reader knows which side of the gate they are standing on. - Put the
neverassignment in every switch over a union:const unreachable: never = valuein thedefaultbranch costs two lines and converts a future runtime surprise into a build failure with a file and a line number. - Write
: neveron helpers that always throw: The annotation is what lets the compiler treat the code after the call as unreachable. Without it the helper is inferred asvoidand you will be asked to handle paths that cannot happen. - Assert to the narrowest useful type: Inside a guard,
value as Record<string, unknown>keeps the field valuesunknownand forces you to check each one;value as Palletskips straight to the conclusion. If an assertion is unavoidable, make it the smallest one that lets the next line run. - Keep
useUnknownInCatchVariableson and share one error formatter: Writefunction messageOf(err: unknown): stringonce, testingerr instanceof Errorand falling back toString(err), and use it everywhere instead of annotatingcatch (err: any)at each site.
Practice Exercises
- The Leak, Then the Gate: Write
const raw: any = "42"; const total: number = raw + 1;and printtotalandtypeof total. Then changerawtounknownand make the file compile again without usingas. Write one sentence naming what the compiler asked you to do that it had not asked before. - The Honest Guard: Write
function isStringArray(value: unknown): value is string[]usingArray.isArrayandevery, and run it over["a", "b"],["a", 2],"ab"and[]. Say what you decided the empty array should mean, and why a caller might disagree. - The Fourth Zone: Add
"dock"toZonein the intake program and leaveholdTemperaturealone. Record the exact error message and the line it points at, then handle the new zone. Finally, replace theneverassignment withdefault: throw new Error("unhandled zone")and explain who discovers the missing case in each version. - Kill the Duplication: Replace
isPalletandfaultOfwith one function returning either{ ok: true; pallet: Pallet }or{ ok: false; fault: string }, and rewriteintaketo use it. The printed sheet must come out byte for byte identical, which is the only proof that your refactor changed the structure and not the behaviour.