Level 15
Type Guards
Type guards are runtime checks the compiler understands — typeof, instanceof, in, and custom predicates — that narrow broad types like unknown or unions down to something you can safely use.
25 min read + quiz
Narrowing: The Compiler Watches Your Ifs
TypeScript performs control-flow analysis: it tracks the type of each variable through your branches. When you write if (typeof x === 'string'), the compiler knows x is string inside the block and excludes string from x's type in the else branch. This is called narrowing, and it is how union types become ergonomic instead of exhausting.
Narrowing works with typeof for primitives, truthiness checks, equality comparisons, and early returns. A function that starts with if (value == null) return; has narrowed value to non-nullable for the entire rest of the body — a pattern worth internalizing.
The big limitation of typeof: it only distinguishes primitives. Arrays, plain objects, Dates, and Maps all report 'object'. And a famous JavaScript wart carries over — typeof null is also 'object', so always check for null explicitly before treating something as an object.
function format(value: string | number | null): string {
if (value === null) {
return "(empty)";
}
// value: string | number
if (typeof value === "string") {
return value.trim(); // value: string
}
return value.toFixed(2); // value: number
}
console.log(format(" hi "));
console.log(format(3.14159));Each check removes possibilities; the last branch needs no check at all.
instanceof and in
instanceof checks the prototype chain and narrows to class instances: if (err instanceof HttpError) gives you access to err.statusCode. It is the natural guard inside catch blocks, since TypeScript types caught values as unknown under useUnknownInCatchVariables.
The in operator narrows by property presence: if ('radius' in shape) selects the union member that declares radius. It is handy for distinguishing object shapes that share no discriminant field, though a proper discriminated union is usually a better design when you control the types.
Watch out for instanceof across execution contexts: an array created in an iframe or a different Node realm fails arr instanceof Array because each realm has its own Array constructor. Use Array.isArray for arrays — it is realm-safe and narrows correctly.
class HttpError extends Error {
constructor(public statusCode: number, message: string) {
super(message);
}
}
function describeError(err: unknown): string {
if (err instanceof HttpError) {
return "HTTP " + err.statusCode + ": " + err.message;
}
if (err instanceof Error) {
return err.message;
}
return String(err);
}
type Shape = { radius: number } | { width: number; height: number };
function area(s: Shape): number {
if ("radius" in s) {
return Math.PI * s.radius * s.radius;
}
return s.width * s.height;
}instanceof for classes, 'in' for structural differences.
Custom Type Predicates
When your check lives in a helper function, plain boolean returns lose the narrowing: the compiler cannot see inside the function. A type predicate fixes this. Declaring the return type as value is User tells the compiler that a true result proves the claim, so the caller's variable narrows exactly as if the check were inline.
This is the standard tool for validating data at boundaries: JSON.parse results, API responses, message payloads. Write one isUser predicate, and every call site gets both the runtime check and the compile-time narrowing.
A predicate is a promise you must keep. The compiler does not verify that your implementation actually establishes the claimed type — return true unconditionally and you have built a lying cast with extra steps. Keep predicates small, test them, and check every property you claim exists.
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof (value as { id: unknown }).id === "number" &&
"name" in value &&
typeof (value as { name: unknown }).name === "string"
);
}
const raw: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
if (isUser(raw)) {
console.log(raw.name.toUpperCase()); // raw: User here
}value is User transfers your runtime check into the type system.
Discriminated Unions: Guards by Design
The most robust narrowing does not need clever guards at all — it is designed into the data. A discriminated union gives every variant a common literal-typed field (conventionally kind, type, or status). Switching on that field narrows perfectly, and the check is a cheap string comparison.
This pattern pairs with exhaustiveness checking. In the default case of a switch, assign the value to a variable of type never. If someone later adds a variant and forgets to handle it, the assignment fails to compile — the type system finds every unhandled case for you across the whole codebase.
Prefer discriminated unions over property-presence checks whenever you control the type definitions. Presence checks ('radius' in s) break silently if two variants ever share a property name; a discriminant field cannot collide because its literal values are distinct by construction.
type Message =
| { kind: "text"; body: string }
| { kind: "image"; url: string; alt: string }
| { kind: "system"; code: number };
function renderMessage(msg: Message): string {
switch (msg.kind) {
case "text":
return msg.body;
case "image":
return "[image: " + msg.alt + "]";
case "system":
return "[system " + msg.code + "]";
default: {
const unhandled: never = msg; // compile error if a variant is missed
return unhandled;
}
}
}The never trick turns missing cases into compile errors.
Assertion Functions
An assertion function is a guard that throws instead of returning false. Declaring asserts value is User means: if this function returns normally, the compiler may assume value is User from that point on. It suits contexts where an invalid value is a bug, not an expected case.
The parameterless form, asserts condition, powers general-purpose assert helpers: after assert(user !== null), the compiler narrows user to non-null. Node's built-in assert module is typed this way.
Choose predicates when the caller has a sensible false path (show a validation error, skip the item) and assertions when failure should halt the operation (corrupted state, impossible input). Both share the same trust model: the compiler believes your signature, so the implementation must actually check.
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error("Assertion failed: " + message);
}
}
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error("Expected a string");
}
}
function shout(input: unknown): string {
assertIsString(input);
return input.toUpperCase(); // input: string from here on
}
const config: { name?: string } = { name: "app" };
assert(config.name, "name is required");
console.log(config.name.length); // narrowed to stringAfter an assertion returns, the compiler trusts the claim permanently.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
Why does moving a typeof check into a helper that returns boolean break narrowing at the call site?
Question 2 · Predict the output
What does this program print?
function classify(value: string | number | string[]): string {
if (typeof value === "object") {
return "array of " + value.length;
}
if (typeof value === "string") {
return "string of " + value.length;
}
return "number " + value;
}
console.log(classify(["a", "b", "c"]));Question 3 · Find the error
This type predicate compiles but is dangerously wrong. What is the flaw?
interface Order {
id: string;
total: number;
}
function isOrder(value: unknown): value is Order {
return typeof value === "object" && value !== null;
}Question 4 · True or false
In a switch over a discriminated union, assigning the value to a variable typed never in the default case causes a compile error whenever a new variant is added but not handled.
Question 5 · Multiple choice