Skip to content

TypeScript narrowing: null checks, guards, assertions

A declared type is often wider than what you know at a given line: a lookup returns Order | undefined, an API payload is unknown, an event is one of five kinds. Narrowing is how TypeScript follows your runtime checks through the code. After if (order === undefined) return;, the compiler knows order is an Order for the rest of the function. This control-flow analysis is the reason TypeScript can be strict without being verbose.

This hub starts with strictNullChecks, which makes null and undefined part of the type system, then covers the checks the compiler understands (type guards), the most useful modeling pattern built on them (discriminated unions) and, last, the escape hatches that override the compiler (as, !) next to the safer satisfies. Read Core type system first if union types are new to you.

Every sample is a complete ES module from an invented online shop, OrdersPortal, compiled with TypeScript 7.0.2 (tsc --strict --target es2025 --module nodenext) and run with Node.js 22. Save one as sample.ts next to a package.json containing {"type": "module"}, compile it with npx tsc --strict sample.ts and run node sample.js. Compiler errors are quoted as tsc prints them, without the file and line prefix.

Topic Since Use it when
Strict null checks TypeScript 2.0 Always: it makes “may be missing” visible in types.
Type guards 1.4; predicates 1.6; in 2.7 You need to know which member of a union a value is.
Discriminated unions TypeScript 2.0 A value is one of several shapes tagged by a literal property.
Type assertions as 1.6; ! 2.0; satisfies 4.9 You know more than the compiler, or want a check without widening.

The strictNullChecks option arrived in TypeScript 2.0 and is part of the strict family, which is on by default since TypeScript 6.0. With it on, null and undefined are separate types: string no longer accepts null, and a value that may be missing has to say so, as string | undefined or with an optional property (email?: string). Library types follow suit: Array.prototype.find returns T | undefined and Map.prototype.get returns V | undefined.

The compiler then refuses to let you use a possibly missing value until you check it. Any check works: if (x), x !== undefined, an early return, optional chaining (x?.name) or a default with ??. Optional chaining and nullish coalescing are JavaScript operators with TypeScript support since 3.7; for their runtime behavior see optional chaining and nullish coalescing.

Without this option, every type silently includes null and undefined, and the most common runtime error in JavaScript, reading a property of undefined, goes unreported.

interface Customer {
id: string;
name: string;
email?: string;
}
const customers: Customer[] = [
{ id: "C-1", name: "Ada Lopez" },
{ id: "C-2", name: "Ben Ortiz", email: "ben@example.test" },
];
function contactLine(id: string): string {
const customer = customers.find((c) => c.id === id); // Customer | undefined
if (customer === undefined) {
return `${id}: not found`;
}
// Narrowed to Customer from here on.
const email = customer.email ?? "(no email on file)";
return `${customer.name}: ${email.toLowerCase()}`;
}
for (const id of ["C-1", "C-2", "C-9"]) {
console.log(contactLine(id));
}

Output:

Ada Lopez: (no email on file)
Ben Ortiz: ben@example.test
C-9: not found

Removing the if block makes the compiler stop at customer.name: error TS18048: 'customer' is possibly 'undefined'.

Pitfalls:

  • Narrowing does not survive callbacks. A check on a let variable or a property is not trusted inside a callback created afterward, because the value could change before it runs. Copy the narrowed value into a const first.
  • Optional is not the same as | undefined. With exactOptionalPropertyTypes (TypeScript 4.4, not in strict), email?: string means “absent or a string”, and explicitly assigning undefined is an error.

Type guards are expressions the compiler uses to narrow a union. typeof and instanceof checks have narrowed since TypeScript 1.4, user-defined type guards (functions returning value is Type) arrived in 1.6, and the in operator narrows since 2.7. Equality checks (===, !==), truthiness checks and Array.isArray narrow as well.

A type predicate is a function whose return type is value is T. When it returns true, the caller’s argument is narrowed to T. This is how you validate unknown data, such as a parsed JSON body, before using it. The compiler trusts the predicate completely; if its body checks the wrong thing, the narrowed type is wrong. Since TypeScript 5.5 the compiler also infers a predicate for simple functions such as (x) => x !== undefined, which is why array.filter((x) => x !== undefined) now returns a narrowed array.

An assertion function (TypeScript 3.7) has the return type asserts value is T: instead of returning a boolean, it throws when the check fails, and the code after the call is narrowed.

class PaymentDeclinedError extends Error {
constructor(public readonly reason: string) {
super(`Payment declined: ${reason}`);
}
}
interface OrderPayload {
id: string;
total: number;
}
function isOrderPayload(value: unknown): value is OrderPayload {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "string" &&
"total" in value &&
typeof value.total === "number"
);
}
function describe(result: OrderPayload | Error | string): string {
if (typeof result === "string") return `message: ${result}`;
if (result instanceof PaymentDeclinedError) return `declined (${result.reason})`;
if (result instanceof Error) return `error: ${result.message}`;
return `order ${result.id} = ${result.total.toFixed(2)}`;
}
const bodies = ['{"id":"ORD-1042","total":59.9}', '{"id":1042}'];
for (const body of bodies) {
const parsed: unknown = JSON.parse(body);
console.log(isOrderPayload(parsed) ? describe(parsed) : `rejected ${body}`);
}
console.log(describe(new PaymentDeclinedError("card expired")));
console.log(describe("queued"));
// Inferred type predicate (TypeScript 5.5): the result is string[], not (string | undefined)[].
const emails = ["ada@example.test", undefined, "ben@example.test"].filter((e) => e !== undefined);
console.log(emails.map((e) => e.toUpperCase()).join(", "));

Output:

order ORD-1042 = 59.90
rejected {"id":1042}
declined (card expired)
message: queued
ADA@EXAMPLE.TEST, BEN@EXAMPLE.TEST

Pitfalls:

  • Order matters with instanceof. Check the subclass (PaymentDeclinedError) before the base class (Error), or the subclass branch never runs.
  • A predicate is a promise you make. function isOrder(x: unknown): x is Order { return true; } compiles. For large payloads, use a schema validation library that derives the type from the schema rather than hand-written predicates.
  • typeof null is "object". Always pair typeof value === "object" with value !== null, as in the sample.

Discriminated unions (also called tagged unions) arrived in TypeScript 2.0. Each member of the union is an object type with a common property, the discriminant, whose type is a different literal in each member: kind: "card", kind: "invoice". Checking the discriminant, with if or switch, narrows the whole object to one member, so its specific properties become available.

This is the TypeScript way to model “one of several cases, each with its own data”, where other languages use sealed class hierarchies or enums with payloads. Combined with the never type, it also gives you exhaustiveness checking: in the default branch of a switch that handles every case, the value has type never. Assigning it to a never variable compiles only while every case is handled, so adding a new member to the union produces a compile error at every switch that forgot it.

type Payment =
| { kind: "card"; last4: string; amount: number }
| { kind: "invoice"; dueDays: number; amount: number }
| { kind: "voucher"; code: string };
function assertNever(value: never): never {
throw new Error(`Unhandled payment: ${JSON.stringify(value)}`);
}
function describePayment(payment: Payment): string {
switch (payment.kind) {
case "card":
return `card ending ${payment.last4}: ${payment.amount} EUR`;
case "invoice":
return `invoice due in ${payment.dueDays} days: ${payment.amount} EUR`;
case "voucher":
return `voucher ${payment.code}`;
default:
return assertNever(payment);
}
}
const payments: Payment[] = [
{ kind: "card", last4: "4242", amount: 59.9 },
{ kind: "invoice", dueDays: 30, amount: 1200 },
{ kind: "voucher", code: "WELCOME10" },
];
payments.forEach((p) => console.log(describePayment(p)));

Output:

card ending 4242: 59.9 EUR
invoice due in 30 days: 1200 EUR
voucher WELCOME10

If you add | { kind: "paypal"; email: string } to Payment without a new case, compilation fails at the default branch: error TS2345: Argument of type '{ kind: "paypal"; email: string; }' is not assignable to parameter of type 'never'.

Pitfalls:

  • Destructuring too early loses the link. Since TypeScript 4.6, destructured discriminants still narrow sibling variables when they are const, but narrowing works most reliably when you check payment.kind on the object itself.
  • Use a literal type for the tag. A discriminant typed as string instead of "card" narrows nothing.
  • Validate at the boundary. Data from an API is not a Payment until you have checked it; an unknown kind would reach assertNever at run time.

Type assertions tell the compiler to treat a value as a type you choose. The as syntax arrived in TypeScript 1.6 (the older <Type>value form cannot be used in .tsx files and is rejected by erasableSyntaxOnly). The non-null assertion value! (TypeScript 2.0) removes null and undefined from a type. Neither produces any runtime code or check: they only change what the compiler believes, so a wrong assertion becomes a runtime error later, far from its cause.

The compiler rejects assertions between types that do not overlap: "ORD-1" as number fails with error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other.; the double assertion as unknown as T bypasses even that, and is a code-review red flag. Legitimate uses are narrow: a DOM element you know exists, a value from a well-typed library whose type is too wide, or the final step of a validated parse.

The satisfies operator (TypeScript 4.9) is often what you actually want. value satisfies Type checks that the value is assignable to Type, reports missing or misspelled properties, and keeps the value’s own, more specific inferred type. Unlike as, it can never hide an error.

type Currency = "EUR" | "USD" | "GBP";
// satisfies: checked against the wider type, but keeps literal keys and number values.
const vatRates = {
EUR: 0.21,
USD: 0,
GBP: 0.2,
} satisfies Record<Currency, number>;
// as: no check of the actual data. Fine only after validation.
const raw = '{"id":"ORD-1042","total":59.9}';
const order = JSON.parse(raw) as { id: string; total: number };
const lookup = new Map<string, number>([["ORD-1042", 2]]);
const lineCount = lookup.get(order.id)!; // non-null assertion: we just inserted it
const gross = order.total * (1 + vatRates.EUR);
console.log(`${order.id}: ${lineCount} lines, gross ${gross.toFixed(2)} EUR`);

Output:

ORD-1042: 2 lines, gross 72.48 EUR

With satisfies, a typo is caught: writing EURO: 0.21 instead of EUR: 0.21 fails with error TS2561: Object literal may only specify known properties, but 'EURO' does not exist in type 'Record<Currency, number>'. Did you mean to write 'EUR'? With as Record<Currency, number> instead, a missing key would compile.

Pitfalls:

  • as on JSON.parse is not validation. It documents an assumption. Use a type guard (above) or a schema validator for data from outside the process.
  • ! spreads. Each non-null assertion is a place where strictNullChecks is switched off. Prefer an explicit check that throws a meaningful error.
  • Use satisfies for configuration objects. An annotation (const vatRates: Record<Currency, number>) widens the type and forgets which keys exist; satisfies checks without widening.
  • To handle a value that may be missing, check it (if, ?., ??) and let strictNullChecks narrow it. Do not reach for ! first.
  • To tell members of a union apart, use typeof for primitives, instanceof for classes, in or a type predicate for plain objects.
  • To model “one of several cases with different data”, use a discriminated union with an exhaustive switch.
  • To check a literal against a type without losing its specific type, use satisfies.
  • Use as only where you hold information the compiler cannot see, and keep it next to the check that justifies it.

What does strictNullChecks change, and why is it the most valuable strict option? It removes null and undefined from every other type, so a possibly missing value must be declared (T | undefined) and checked before use. That catches “cannot read properties of undefined” errors, the most common runtime failure in JavaScript code, at compile time. Since TypeScript 6.0 it is on by default as part of strict.

What is the difference between a type predicate and an assertion function? A type predicate (x is T) returns a boolean and narrows the argument in the true branch of the caller’s condition. An assertion function (asserts x is T) returns nothing and throws if the check fails, so the argument is narrowed for all code after the call.

How does exhaustiveness checking with never work? In a switch over a discriminated union, each case removes one member from the type. If every case is handled, the value’s type in default is never, which can be passed to a never parameter. When a new member is added, the value in default has that member’s type, which is not assignable to never, so the compiler reports an error.

When would you use satisfies instead of a type annotation? When you want the compiler to check a value against a type but keep the value’s narrower inferred type: for example a configuration object whose keys and literal values you still want in autocompletion and in derived types. An annotation widens the variable to the declared type.

Why is JSON.parse(body) as Order dangerous? as performs no runtime check. If the payload is missing a field or has the wrong type, the code compiles and fails later, wherever the field is used. Parse to unknown and validate with a type guard or schema first.

Senior scenario: OrdersPortal’s checkout has if (payment.type === "card") ... else ... chains spread across eight files, and adding PayPal caused silent fallthrough into the invoice branch. How would you restructure it? Model the payment as a discriminated union with a literal kind, and replace the if/else chains with switch statements that end in an assertNever default, or with a single Record<Payment["kind"], Handler> map so a missing handler is a compile error. Validate incoming payment data at the API boundary into that union. Adding a member then fails compilation everywhere a case is missing instead of falling through at run time.