Difficulty: Intermediate
What are type guards in TypeScript, and how does the compiler narrow a union type based on runtime checks like `typeof`, `instanceof` and `in`?
A type guard is a runtime check that TypeScript understands well enough to narrow a variable's type inside the guarded block. After if (typeof id === "string"), the compiler treats id as string in that branch and as the remaining union members in the else. This process is called control flow narrowing, and it is how you work safely with unions without casting.
typeof x === "string" | "number" | "boolean" | "bigint" | "symbol" | "undefined" | "function" | "object" for primitives. Remember typeof null === "object", so check x !== null too.x instanceof Date for class instances; it checks the prototype chain."refund" in event narrows unions of object types by property presence.x === null, x == null (covers undefined too), or comparing a literal discriminant like shape.kind === "circle".if (user) removes null and undefined, but also 0 and "", which bites with amounts in paise or empty strings.Array.isArray(x) narrows to an array type.The compiler tracks every assignment and condition along each code path. Early returns narrow everything after them, switch cases narrow per branch, and && and || narrow their right-hand sides. Narrowing resets when a variable is reassigned, and it does not survive into callbacks for let variables because the callback could run later after reassignment. Using const or copying to a local fixes that.
When the check is too complex for the built-ins, write a function returning value is Type. TypeScript trusts this predicate completely, so a buggy guard is as dangerous as a wrong cast. Since TypeScript 5.5 the compiler can infer simple predicates automatically, so arr.filter(x => x !== undefined) now returns T[] instead of (T | undefined)[].
Assertion functions (asserts value is Type) are the throwing variant: after calling assertIsUser(x), the rest of the scope sees x as User. They pair well with validation libraries.
event.type decides the shape.unknown from JSON.parse or a catch (err) clause with err instanceof Error.Promise.allSettled outcomes by status === "fulfilled".0 or "".instanceof to work on interfaces or type aliases; they do not exist at runtime.type Amount = number | string | null;
function toPaise(amount: Amount): number {
if (amount === null) return 0; // null removed below
if (typeof amount === "string") {
return Math.round(parseFloat(amount) * 100); // amount: string
}
return Math.round(amount * 100); // amount: number
}
class ApiError extends Error { constructor(public status: number) { super(); } }
function handle(err: unknown) {
if (err instanceof ApiError) return err.status; // ApiError
if (err instanceof Error) return err.message; // Error
return String(err); // unknown
}
Equality, typeof and instanceof checks each narrow the union along their branch. In catch blocks errors are unknown by default under strict, so instanceof is the standard narrowing tool.
interface CardPayment { cardLast4: string }
interface UpiPayment { vpa: string }
type Payment = CardPayment | UpiPayment;
function describe(p: Payment) {
if ("vpa" in p) return `UPI ${p.vpa}`; // UpiPayment
return `Card ending ${p.cardLast4}`; // CardPayment
}
// Custom type guard with a type predicate
function isUpi(p: Payment): p is UpiPayment {
return typeof (p as UpiPayment).vpa === "string";
}
const payments: Payment[] = [{ vpa: "asha@okaxis" }, { cardLast4: "4242" }];
const upiOnly = payments.filter(isUpi); // UpiPayment[]
The in operator narrows object unions by property presence. A predicate function lets you reuse a check, and filter uses it to narrow the array type.
function assertIsString(v: unknown, name: string): asserts v is string {
if (typeof v !== "string") throw new TypeError(`${name} must be a string`);
}
function readEnv(key: string): string {
const value = process.env[key]; // string | undefined
assertIsString(value, key);
return value; // string from here on
}
// TypeScript 5.5+ infers the predicate for simple arrow functions
const ids = ["a", undefined, "b"].filter((x) => x !== undefined);
// ^? string[] (was (string | undefined)[] before 5.5)
An asserts signature narrows everything after the call or throws. From TypeScript 5.5 the compiler infers type predicates for simple filter callbacks.
Type Guards, Control Flow Narrowing, Type Predicates, instanceof, in Operator, Assertion Functions