Skip to content
jshacks.dev
TypeScript

Type Narrowing in TypeScript

Narrowing turns a broad type into a precise one inside a branch. Learn typeof, in, instanceof, discriminants, type predicates, assertion functions and pitfalls.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, npm, Node.js and Vite logos.

A union type says a value could be one of several things, and a union is only useful if you can find out which one you have. Type narrowing is how the compiler follows your checks. When you write if (typeof value === "string"), the compiler understands that inside the block value is a string, and after the block it is whatever is left. The same machinery handles instanceof, in, equality tests, truthiness, tag properties and your own predicate functions. It is also the reason a codebase with few type assertions can still have precise types: the checks you wrote anyway are doing the work. This post covers each narrowing form with the exact errors, the pitfalls that catch people, and how to test narrowing code. It uses TypeScript 6.x with strict on, and the reference is the narrowing handbook page.

typeof and truthiness

The typeof operator narrows primitives. The compiler recognizes the results "string", "number", "bigint", "boolean", "symbol", "undefined", "object" and "function".

typeof-narrow.tsTypeScript
function format(value: string | number | undefined): string {
  if (typeof value === "string") {
    return value.trim();
  }
  if (typeof value === "number") {
    return value.toFixed(2);
  }
  return value.toString();
}
Text
typeof-narrow.ts(8,10): error TS18048: 'value' is possibly 'undefined'.

Each branch removes a member. After the two if blocks, only undefined is left, and calling a method on it is refused, which is correct: the code forgot to handle the case. Changing the last line to return "n/a"; fixes it.

Truthiness narrows too, and it has a well-known trap. A truthiness check removes undefined, null and also every falsy value of the other members.

truthy.tsTypeScript
function describeCount(count: number | undefined): string {
  if (count) {
    return `${count} items`;
  }
  return "no count";
}

console.log(describeCount(5));
console.log(describeCount(undefined));
console.log(describeCount(0));
Text
5 items
no count
no count

The compiler narrows count to number inside the block, and that is accurate. The bug is in the logic: zero is falsy, so a real count of zero is reported as missing. When a value can legitimately be 0, "" or false, test for what you mean, as in count !== undefined.

Equality and in

An equality check narrows to the literal types the compared values share, and x != null removes both null and undefined in one step. The in operator narrows by property name.

in-narrow.tsTypeScript
type Cat = { meow(): string };
type Dog = { bark(): string };

function speak(pet: Cat | Dog): string {
  if ("meow" in pet) {
    return pet.meow();
  }
  return pet.bark();
}

console.log(speak({ meow: () => "mew" }));
console.log(speak({ bark: () => "woof" }));
Text
mew
woof

In the true branch, pet is Cat, because only Cat has meow, and after the early return pet must be Dog. This works well for unions of distinct shapes. It is weaker when two members share the property, because the check cannot tell them apart, and when an object might have extra properties at runtime, since in tests the actual object, not its declared type.

instanceof

instanceof narrows to the class on the right. It works for built-ins such as Date and Error, and for your own classes.

instance.tsTypeScript
class ValidationError extends Error {
  constructor(readonly field: string) {
    super(`invalid ${field}`);
  }
}

function report(error: unknown): string {
  if (error instanceof ValidationError) {
    return `field=${error.field}`;
  }
  if (error instanceof Error) {
    return error.message;
  }
  return "unknown failure";
}

console.log(report(new ValidationError("email")));
console.log(report(new RangeError("too big")));
console.log(report("oops"));
Text
field=email
too big
unknown failure

The check order matters. ValidationError extends Error, so testing Error first would catch both, and the specific branch would never run. Put the most specific class first. This pattern is also the standard way to handle a catch clause variable, which is unknown under strict.

Discriminated unions

When every member of a union carries a literal property with a different value, checking that property narrows the whole object. It is the most reliable form, and it scales to many members.

result.tsTypeScript
type Success = { ok: true; value: number };
type Failure = { ok: false; reason: string };
type Result = Success | Failure;

function unwrap(result: Result): number {
  if (result.ok) {
    return result.value;
  }
  throw new Error(result.reason);
}

console.log(unwrap({ ok: true, value: 42 }));

try {
  unwrap({ ok: false, reason: "not found" });
} catch (error) {
  console.log(error instanceof Error ? error.message : "unknown");
}
Text
42
not found

The ok property is the discriminant, and a boolean literal is enough. A switch over a string tag works the same way and can end with a never check so that adding a member breaks the build, which the post on any, unknown and never shows.

Type predicates

When the check is too involved for the built-in forms, write a function whose return type is a predicate, value is Type. The compiler trusts it.

predicate.tsTypeScript
type 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"
  );
}

const raw: unknown = JSON.parse('{"id":7,"name":"Ada"}');
if (isUser(raw)) {
  console.log(raw.name.toUpperCase(), raw.id + 1);
}
console.log(isUser({ id: "7", name: "Ada" }));
Text
ADA 8
false

The function body narrows step by step: typeof value === "object" and the null check give object, and the in operator then lets the compiler read value.id as unknown, which typeof narrows to number. The predicate return type then carries the result to the caller. The risk is that nothing checks the predicate against the type. A predicate that returns true too eagerly makes the compiler believe a falsehood, so write one carefully, test it, and keep it next to the type it guards.

Assertion functions

An assertion function narrows by throwing. Its return type is asserts value is Type, and code after a call to it sees the narrowed type.

assert.tsTypeScript
function assertString(value: unknown): asserts value is string {
  if (typeof value !== "string") {
    throw new TypeError(`expected string, got ${typeof value}`);
  }
}

function shout(input: unknown): string {
  assertString(input);
  return input.toUpperCase();
}

console.log(shout("hello"));

try {
  shout(42);
} catch (error) {
  console.log(error instanceof Error ? error.message : "unknown");
}
Text
HELLO
expected string, got number

After assertString(input), input is a string for the rest of the function. A caveat applies: the function must be declared with an explicit type annotation to be used in this way, which a function declaration satisfies. Assertion functions suit input validation at the top of a function, where failing fast is what you want anyway.

Inferred predicates

TypeScript 5.5 added inferred type predicates: when a function's body is a simple check, the compiler infers the predicate itself. The visible effect is on filter.

filter.tsTypeScript
const values: Array<number | undefined> = [1, undefined, 3];

const present = values.filter((value) => value !== undefined);
const total = present.reduce((sum, value) => sum + value, 0);

console.log(present);
console.log(total);
Text
[ 1, 3 ]
4

Before 5.5, present was still (number | undefined)[], and the reduce line failed, so people wrote an explicit predicate or an assertion. Now the compiler infers value is number from value !== undefined. The inference applies only when the check is exact in both directions: a callback that tests truthiness would not qualify, since a falsy 0 is also removed, and the type would stay as it was. The TypeScript 5.5 release notes describe the rules.

When narrowing is lost

Narrowing follows control flow, and a few things reset it. Reassigning a variable replaces the narrowed type with the declared one's matching member. A narrowed let captured by a callback may not stay narrowed, because the compiler cannot be sure the callback runs before another assignment. The simplest fix is to copy the narrowed value into a const before the callback.

lost.tsTypeScript
function schedule(task: (() => string) | undefined): string[] {
  const results: string[] = [];
  if (task) {
    const run = task;
    [1, 2].forEach(() => results.push(run()));
  }
  return results;
}

console.log(schedule(() => "done"));
console.log(schedule(undefined));
Text
[ 'done', 'done' ]
[]

Here task is a parameter that is never reassigned, so the compiler can keep the narrowing, and the const run copy is defensive rather than required in this exact case. The habit pays off when the variable is a let that changes elsewhere. Property narrowing is also optimistic: after if (user.email), a call to any function does not undo the narrowing of user.email, even though the function could change it. This is a deliberate trade-off for usability, and it means narrowing on a mutable object is only as reliable as your code's discipline.

Testing narrowing code

A narrowing function is a pure function with a branch for each member, which makes it easy to test with one case per branch. Cover the boundary values the types make easy to forget, such as zero, the empty string and null.

format.test.tsTypeScript
import { strictEqual } from "node:assert/strict";

function label(value: string | number | null): string {
  if (value === null) return "none";
  if (typeof value === "number") return value.toFixed(1);
  return value === "" ? "empty" : value;
}

strictEqual(label(null), "none");
strictEqual(label(0), "0.0");
strictEqual(label(""), "empty");
strictEqual(label("abc"), "abc");
console.log("all branches checked");
Text
all branches checked

The zero and empty-string cases are the ones a truthiness check would have gotten wrong, so they are the cases worth pinning.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.