Skip to content
FrontDepth, Home

TypeScript

Narrowing, type guards and unknown

How TypeScript refines union types from ordinary JavaScript checks (typeof, truthiness, equality, in, instanceof), how control-flow analysis follows them and where it stops, unknown and caught errors, discriminated unions with exhaustiveness checks, and type guards that can lie.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Union types and narrowing

A value in JavaScript often has more than one possible type. A function may accept an id as a string or a number; document.querySelector returns an element or null; an optional parameter is a value or undefined. TypeScript writes this as a union type, with |:

TypeScript
function formatId(id: string | number): string {
  return id.toUpperCase();
  // error: Property 'toUpperCase' does not exist on type 'string | number'.
  //   Property 'toUpperCase' does not exist on type 'number'.
}

A value of a union type could be any of its members, so TypeScript allows only what every member supports. id.toString() is fine, because strings and numbers both have it; toUpperCase exists only on strings.

To use the parts that belong to one member, check which member you have, with ordinary JavaScript:

TypeScript
function formatId(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase(); // here id is string
  }
  return id.toFixed(0); // here id is number
}

Inside the if, TypeScript knows that id is a string; after it, only number is left. Refining a declared type to a more specific one based on checks in the code is called , and the checks that do it are called . Nothing new happens at run time: typeof id === "string" is plain JavaScript, and TypeScript reads it the way you do.

Unions of literal types are just as common:

TypeScript
type Theme = "light" | "dark" | "system";

function applyTheme(theme: Theme) {
  if (theme === "system") {
    // theme is "system"
  } else {
    // theme is "light" | "dark"
  }
}

With strictNullChecks on, null and undefined are union members like any other: a string | null has to be narrowed before you call a string method on it. That is where most narrowing in everyday code happens: the element that may not exist, the optional prop, the result of find.

The rest of this topic is about which checks TypeScript understands, how it follows them through your code, and where it stops following.

JuniorConcept

typeof and truthiness checks

typeof returns one of a fixed set of strings, and TypeScript narrows on each of them: "string", "number", "bigint", "boolean", "symbol", "undefined", "object" and "function".

TypeScript
function padLeft(padding: number | string, input: string): string {
  if (typeof padding === "number") {
    return " ".repeat(padding) + input;
  }
  return padding + input;
}

The typeof null trap

In JavaScript, typeof null is "object", a historical accident that TypeScript models faithfully:

TypeScript
function printAll(items: string[] | null) {
  if (typeof items === "object") {
    for (const item of items) console.log(item);
    // error: 'items' is possibly 'null'.
  }
}

The check narrowed items to string[] | null, not to string[]. Compare with null explicitly (items !== null), or use Array.isArray(items), which narrows to the array.

Truthiness

if (value) narrows too: in the true branch, null and undefined are gone. The falsy values in JavaScript are false, 0, -0, 0n, "", NaN, null and undefined (plus the legacy document.all), and the trap is that some of them are valid data:

TypeScript
function unreadLabel(count: number | undefined): string {
  if (count) return `${count} unread`;
  return "Loading...";
}

unreadLabel(0); // "Loading...", although we know there are 0 unread

TypeScript accepts this code. In the false branch count is still number | undefined, because a number can be falsy: the types are right, the logic is wrong. When a value can legitimately be 0, "" or NaN, say what you mean:

TypeScript
if (count !== undefined) return `${count} unread`;

The same applies to defaults: count || 10 replaces 0 with 10, while count ?? 10 replaces only null and undefined.

Truthiness is the right check for objects and arrays, which are truthy even when empty: with user: User | null, if (user) safely means "the user exists". For strings and numbers, prefer explicit comparisons.

JuniorConcept

Equality, in and instanceof

Equality. Comparing with ===, !==, == or != narrows. A comparison with a literal narrows to that literal, as with theme === "system". Loose equality with null is the one place where == is idiomatic: value != null excludes both null and undefined.

TypeScript
function displayName(name: string | null | undefined): string {
  if (name != null) {
    return name.trim(); // string
  }
  return "Anonymous";
}

The in operator checks whether an object has a property, and narrows a union to the members that have it:

TypeScript
type Fish = { name: string; swim(): void };
type Bird = { name: string; fly(): void };

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    animal.swim(); // Fish
  } else {
    animal.fly(); // Bird
  }
}

If a member declares the property as optional, it stays on both sides, because the property may or may not be there.

instanceof narrows to a class: value instanceof Date, error instanceof TypeError, event.target instanceof HTMLInputElement. It works because classes exist at run time, and it doesn't work for interfaces or type aliases, which don't.

TypeScript
function toDate(input: Date | string): Date {
  return input instanceof Date ? input : new Date(input);
}

function onInput(event: Event) {
  if (event.target instanceof HTMLInputElement) {
    console.log(event.target.value); // event.target is HTMLInputElement
  }
}

Two cautions. instanceof checks the prototype chain, so it fails across realms: an array created in an iframe is not instanceof Array in the main window, which is why Array.isArray exists, and TypeScript narrows on it too. And an object that merely has the right shape isn't an instance: a plain object passed where a class type is expected passes the type check but fails instanceof.

Choosing the check

  • A primitive (string, number, boolean, undefined): typeof.
  • null, or a literal value: === or !==; != null for both null and undefined.
  • Object types that differ by a property: in, or better a shared literal field, covered in the middle sections.
  • Class instances, built-in objects, DOM elements: instanceof.
  • Arrays: Array.isArray.

Each of these is plain JavaScript that you would write anyway. TypeScript's contribution is to remember the result for the code that follows.

MiddleConcept

Control-flow analysis

TypeScript doesn't only look at the nearest if. It follows every path through a function (returns, throws, assignments, &&, ||, ?:, loops) and computes the type of each variable at each point. The handbook calls this control-flow analysis.

Early returns narrow everything after them, which keeps the main path flat:

TypeScript
function sendWelcome(user: User | null, email: string | undefined) {
  if (!user) return;
  if (email === undefined) throw new Error("No email");

  // here user is User and email is string
  mailer.send(email, `Welcome, ${user.name}`);
}

Assignments narrow to the assigned type, within the declared type:

TypeScript
let input: string | number = readInput();
input = String(input); // from here on, input is string
input.trim();

Conditions stored in constants work as well, as long as what they test can't change: a const, a readonly property, or a parameter that is never assigned.

TypeScript
function shout(value: unknown) {
  const isText = typeof value === "string";
  if (isText) {
    return value.toUpperCase(); // value is string
  }
}

&&, || and ?: narrow their right-hand side and branches: in user !== null && user.name.length > 0, user is a User after the &&.

Narrowing belongs to a reference

Each narrowing is tied to a reference: a variable, a parameter, or a property path such as order.customer.address. TypeScript keeps the narrowing of that path until something assigns to it or to one of its parents:

TypeScript
if (order.customer.address !== null) {
  order.customer.address.city; // Address
  order.customer = loadCustomer();
  order.customer.address.city;
  // error: 'order.customer.address' is possibly 'null'.
}

The assignment to order.customer resets the narrowing of everything below it, which is exactly right: the new customer may have no address.

This is what makes narrowing feel natural: you write the checks you would write in JavaScript anyway, and the types follow. It is also why the analysis has limits. TypeScript reasons about one function at a time and doesn't look inside the functions you call or the callbacks you pass, so it can't know everything that happens to a value between the check and the use. The next section shows where that matters.

MiddlePitfalls

Where narrowing is lost

Three situations break the link between a check and a later use. In two of them TypeScript forgets a narrowing you can see; in the third, it keeps a narrowing that is no longer true.

1. A property read inside a callback. A callback may run later, when the property could have changed, so TypeScript drops the narrowing of a property path inside it:

TypeScript
function notifyAll(session: Session, ids: string[]) {
  if (session.user !== null) {
    ids.forEach((id) => {
      send(id, session.user.name);
      // error: 'session.user' is possibly 'null'.
    });
  }
}

Copy the value into a const right after the check: const user = session.user;. A const can't be reassigned, so its narrowing holds in every callback.

2. A let variable or parameter that is assigned again. Since TypeScript 5.4, the narrowing of a let variable or a parameter carries into a closure created after its last assignment:

TypeScript
function schedule(label: string | undefined) {
  if (label === undefined) label = "untitled";
  setTimeout(() => console.log(label.toUpperCase())); // OK: no assignment after this
}

Assign label again after the setTimeout line, or anywhere inside a nested function, and the closure sees string | undefined again. The fix is the same const copy.

3. A function call that changes what you checked. TypeScript doesn't reset narrowing when you call a function; if every call could undo every check, narrowing would be useless. So this compiles and crashes:

TypeScript
function farewell(session: Session): string {
  if (session.user !== null) {
    signOut(session); // sets session.user = null
    return `Bye, ${session.user.name}`; // compiles; TypeError at run time
  }
  return "Nobody to sign out";
}

The handbook says it plainly: TypeScript allows some operations that can't be known to be safe at compile time, so the type system is not sound. Here the remedy is again a const copy taken before the call, or code that doesn't change shared state behind the reader's back.

What not to do

The tempting fix for the first two cases is the non-null assertion: session.user!.name. It makes the error disappear without proving anything, and in the third case it would even hide the bug. When TypeScript loses a narrowing, ask what could change the value between the check and the use; if the answer is "nothing", copy it into a const, and if it is "something", that is the bug to fix.

MiddleConcept

unknown and caught errors

unknown is the type-safe counterpart of any. Both accept every value; with any you can then do anything, with unknown nothing until you narrow. That makes unknown the right type for values whose shape you haven't checked: parsed JSON, postMessage data, the value in a catch clause.

Narrowing unknown uses the same checks, step by step:

TypeScript
function readName(data: unknown): string | undefined {
  if (
    typeof data === "object" &&
    data !== null &&
    "name" in data &&
    typeof data.name === "string"
  ) {
    return data.name; // string
  }
  return undefined;
}

typeof data === "object" leaves object | null (the typeof null trap again), data !== null leaves object, and since TypeScript 4.9, "name" in data adds a name property of type unknown, which the last check narrows to string. For anything bigger than a couple of fields this gets long, and a schema library becomes the better tool; is its own topic.

Caught errors

Anything can be thrown in JavaScript: an Error, a string, a number, a library's custom object. Under strict (precisely, useUnknownInCatchVariables, added in TypeScript 4.4), the variable of a catch clause is unknown:

TypeScript
async function save(draft: Draft) {
  try {
    await saveDraft(draft);
  } catch (error) {
    console.error(error.message);
    // error: 'error' is of type 'unknown'.

    const message = error instanceof Error ? error.message : String(error);
    showToast(`Could not save: ${message}`);
  }
}

instanceof Error is the usual narrowing, and checking for your own error classes (error instanceof HttpError) lets you handle each kind separately. You can't annotate the variable as Error: TypeScript allows only any or unknown there ("Catch clause variable type annotation must be 'any' or 'unknown' if specified."), because nothing guarantees what was thrown. catch (error: any) opts one clause out and brings back unchecked access: error.message is simply undefined when a string was thrown, and error.message.includes(...) crashes inside your error handler.

any or unknown?

any trusts the value and checks nothing; unknown trusts nothing and makes you check. Use unknown for every value that enters from outside, narrow it once at the boundary, and pass precise types onward. An any is acceptable only where you can explain in a comment why checking is impossible or pointless.

MiddleExample

Discriminated unions and exhaustiveness

A common shape for state is a set of variants, each with a literal field that says which variant it is:

TypeScript
type RequestState =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; error: Error };

When every member has a common property with a literal type, TypeScript treats the union as a , and checking that property narrows the whole object:

TypeScript
function render(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading...";
    case "success":
      return state.data.join(", "); // state has data here
    case "error":
      return state.error.message; // and error here
  }
}

Outside the switch, state.data is an error ("Property 'data' does not exist on type 'RequestState'"), and that is the point. Compare it with one object of optional fields, { loading: boolean; data?: string[]; error?: Error }: it allows "loading, with data and an error" and forces a check of every field everywhere. The union makes such impossible states impossible to write.

Exhaustiveness checks

When a variant is added, every switch over the union has to handle it. Let the compiler find them:

TypeScript
function assertNever(value: never): never {
  throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}

function render(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading...";
    case "success":
      return state.data.join(", ");
    case "error":
      return state.error.message;
    default:
      return assertNever(state);
  }
}

In default, every variant has been ruled out, so state is never and the call compiles. Add { status: "idle" } to the union and the call becomes an error: "Argument of type '{ status: "idle"; }' is not assignable to parameter of type 'never'." The handbook assigns to a variable instead (const _exhaustiveCheck: never = state;), and state satisfies never; works too. Without a default, the return type alone catches a missing case: "Function lacks ending return statement and return type does not include 'undefined'."

The throw in assertNever matters because types are erased. If the server sends a status the union doesn't list, the code reaches default at run time, and a clear error beats a silently wrong screen.

SeniorConcept

Type guards, assertion functions and how they lie

When a check is long or needs a name, move it into a function that returns a type predicate:

TypeScript
interface User {
  id: number;
  name: string;
}

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

if (isUser(data)) {
  data.name; // data is User
}

const users = rows.filter(isUser); // User[]

value is User means: if this returns true, value is a User; if it returns false, it is not. A call narrows like a built-in check, and filter uses the predicate to narrow the array.

An assertion function narrows by throwing instead of returning false:

TypeScript
function assertIsUser(value: unknown): asserts value is User {
  if (!isUser(value)) throw new Error("Expected a user");
}

assertIsUser(data);
data.name; // data is User for the rest of the scope

The other form, asserts condition, works like Node's assert: after assert(root !== null, "No #root"), root is narrowed. One rule surprises people: an assertion function has to be called through a name with an explicit type. A const arrow function without a type annotation on the const, or a method of an untyped object literal, fails with "Assertions require every name in the call target to be declared with an explicit type annotation."

A guard is a claim

TypeScript doesn't check that a guard's body proves its predicate. This compiles:

TypeScript
function isUser(value: unknown): value is User {
  return typeof value === "object" && value !== null; // forgot id and name
}

Every non-null object now passes as a User, and the crash happens far away, where some code calls user.name.trim(). The TypeScript 5.5 release notes say it directly: explicit type predicates are no safer than a type assertion. The only thing the compiler verifies is that the predicate's type is assignable to the parameter's type.

So treat a hand-written guard like an as. Keep guards few and small, check every field the type promises (or derive the check and the type from one schema), and test each guard with input that should fail: an object missing a field, a field of the wrong type, null, a string.

SeniorConcept

Inferred type predicates

Before TypeScript 5.5, filtering out undefined didn't change the array's type:

TypeScript
const nicknames = users.map((u) => u.nickname); // (string | undefined)[]
const present = nicknames.filter((n) => n !== undefined);
// TypeScript 5.5 and later: string[]
// before 5.5: (string | undefined)[]

Since 5.5, TypeScript infers a type predicate for a function like (n) => n !== undefined, as if you had written (n): n is string => .... The release notes list the conditions:

  1. The function has no explicit return type or type predicate annotation.
  2. It has a single return statement and no implicit returns.
  3. It doesn't mutate its parameter.
  4. It returns a boolean expression tied to a refinement on the parameter.

So const isNumber = (x: unknown) => typeof x === "number"; now has the type (x: unknown) => x is number and works as a guard.

True means T, false means not T

A predicate promises both directions: true means the value is T, false means it isn't. That is why a truthiness filter on numbers gets no predicate:

TypeScript
const scores = [90, 0, undefined, 75];
const counted = scores.filter((s) => !!s);
// still (number | undefined)[]: false could also mean 0

TypeScript refuses because the function returns false for 0, which is a number. That is a real bug as well: the zero score disappears from the result. Write the check you mean, s !== undefined, and you get number[] with the zero kept. For object types, where no value is falsy, a truthiness check does infer a predicate: maybeUsers.filter((u) => !!u) gives User[]. filter(Boolean) still doesn't narrow, and neither does (x) => x, which doesn't return a boolean.

Side effects of the inference

The more precise types can break code that relied on the old ones. The release notes' example: [1, 2, 3, null, 5].filter((x) => x !== null) used to be (number | null)[] and is now number[], so a later push(null) no longer compiles. Annotate the variable when you want the wider type.

Explicit predicates behave exactly as before. TypeScript doesn't compare them with what it would infer, so a hand-written x is T can still lie; an inferred one can't, because it is derived from the code.

SeniorInterview tips

Interview tips

A 30-second answer. "Narrowing is how TypeScript refines a union based on checks in the code: typeof, truthiness, equality, in, instanceof and discriminant properties. Control-flow analysis follows returns and assignments, but it drops the narrowing of properties inside callbacks and doesn't reset it after function calls. unknown is the safe type for unchecked data and caught errors. Discriminated unions with a never check make the compiler find unhandled cases. User-defined guards and assertion functions extend narrowing, but the compiler trusts their bodies, so a wrong guard lies like an as."

Questions you are likely to get

  • Why is items still string[] | null after typeof items === "object"? Because typeof null is "object"; compare with null or use Array.isArray.
  • What's wrong with if (count)? It treats 0 (and NaN) like a missing value; compare with undefined.
  • Why does TypeScript complain inside this forEach although I checked for null? Property narrowing is dropped in callbacks; copy the value into a const.
  • What type does a catch variable have? unknown under strict (useUnknownInCatchVariables); narrow with instanceof Error.
  • How do you make sure every case of a union is handled? A discriminated union, a never check in default, and a throw for values that arrive at run time anyway.
  • x is T or asserts x is T? A predicate returns a boolean and narrows inside the branch; an assertion throws and narrows the rest of the scope.
  • What changed for filter in TypeScript 5.5? Inferred type predicates: filter((x) => x !== undefined) now narrows the array.

Mistakes that cost points

  • Calling a type guard a check "of the type". It checks whatever its body checks; TypeScript never verifies that this matches the type.
  • Fixing a narrowing error with ! or as instead of a check or a const copy.
  • Using truthiness on numbers and strings out of habit.
  • Believing an exhaustive switch protects against unexpected data from a server without a runtime branch.

Senior signal

Model state as discriminated unions instead of objects full of optional fields. Keep hand-written guards few, small and tested, or generate them from schemas. Know where the analysis is unsound (function calls, guards, assertions, as, !), so that when a "type-safe" program crashes, you know where to look first.

JuniorReview checklist

What to check when reviewing narrowing and type guards

Use this list when you review TypeScript you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Narrowing mistakes compile cleanly. The checks look right, and the bug appears only for the value nobody tried: a zero, an empty string, a status the server added later.

  • Do truthiness checks run on numbers or strings? if (count), if (!title) and value || fallback treat 0, "" and NaN like missing values. Find them in the diff and ask whether zero or an empty string is valid there; if it is, compare with undefined or null, or use ??.
  • Is a typeof x === "object" check followed by a null check? typeof null is "object", so the check alone lets null through. Look for x !== null next to it, or confirm that the type can't contain null.
  • Does every switch or if chain over a union end in an exhaustiveness check? Look for a default that passes the value to a never parameter and throws. Add a member to the union locally and confirm that tsc reports every place that has to change.
  • Does each hand-written type guard check everything its predicate promises? Compare the body of an x is User function with the User type field by field: a guard that checks one field certifies all of them. Call it with an object that lacks a field and confirm it returns false.
  • Is a narrowing error silenced with ! or as? session.user!.name or data as User where TypeScript didn't accept a check usually hides a real case: a callback that runs later, a function call that changed the value, data that was never validated. Ask for a const copy after the check or a real guard instead.
  • Are caught errors used without narrowing? With catch (error: any) or error as Error, the handler reads error.message from something that may be a string or a plain object. Check that the code tests error instanceof Error (or its own error classes) before using the error's properties.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions