Skip to content
Sign inGet all access
Chapter 3·32 minFree

Narrowing

How the checker follows control flow, and exhaustiveness with never.

typeof

Chapter 2 left a union you could not use. A typeof check is the fix — inside the branch, the type is just string:

app.ts
function format(v: string | number) {
  if (typeof v === "string") {
    return v.toUpperCase()
  }

  return v.toFixed(2)
}

console.log(format("ada"), format(3.14159))
Output$ npx tsc --noEmit app.ts$ echo $?0

The return after the if gets number without a second check. The checker eliminated string by following the control flow:

app.ts
function format(v: string | number) {
  return v.toUpperCase()
}
Output$ npx tsc --noEmit app.tsapp.ts(2,12): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'.

Truthiness

A plain if (n) narrows too, and that is the problem. This compiles clean:

app.ts
function label(n: number | undefined) {
  if (n) {
    return n.toFixed(0)
  }

  return "none"
}

console.log(label(5))
console.log(label(0))
console.log(label(undefined))
Output$ npx tsc --noEmit app.ts$ node app.ts5nonenone

Test for the thing you actually mean:

app.ts
function label(n: number | undefined) {
  if (n !== undefined) {
    return n.toFixed(0)
  }

  return "none"
}

console.log(label(5))
console.log(label(0))
console.log(label(undefined))
Output$ node app.ts50none

Equality

=== against a literal narrows a literal union to one member:

app.ts
function go(role: "admin" | "guest") {
  if (role === "admin") {
    return "all access"
  }

  return role.toUpperCase()
}

console.log(go("admin"), go("guest"))
Output$ npx tsc --noEmit app.ts$ echo $?0

For null and undefined together, loose == is the deliberate exception — it matches both and nothing else:

app.ts
function f(v: string | null | undefined) {
  if (v == null) {
    return "empty"
  }

  return v.toUpperCase()
}

console.log(f(null))
console.log(f(undefined))
console.log(f("ada"))
Output$ node app.tsemptyemptyADA

The in operator

When the members share no primitive type, narrow by which property exists:

app.ts
type Dog = { bark: () => string }
type Fish = { swim: () => string }

function move(pet: Dog | Fish) {
  if ("bark" in pet) {
    return pet.bark()
  }

  return pet.swim()
}

console.log(move({ bark: () => "woof" }))
Output$ npx tsc --noEmit app.ts$ echo $?0

Without the check, neither method is available — only what both types have:

app.ts
type Dog = { bark: () => string }
type Fish = { swim: () => string }

function move(pet: Dog | Fish) {
  return pet.bark()
}
Output$ npx tsc --noEmit app.tsapp.ts(5,14): error TS2339: Property 'bark' does not exist on type 'Dog | Fish'. Property 'bark' does not exist on type 'Fish'.

instanceof

For anything built with a class — Date, Error, your own types:

app.ts
function describe(v: Date | string) {
  if (v instanceof Date) {
    return v.toISOString()
  }

  return v.toUpperCase()
}

console.log(describe(new Date(0)))
console.log(describe("ada"))
Output$ npx tsc --noEmit app.ts$ echo $?0

Inside that branch the type really is Date, so a string method is an error:

app.ts
function describe(v: Date | string) {
  if (v instanceof Date) {
    return v.toUpperCase()
  }

  return v
}
Output$ npx tsc --noEmit app.tsapp.ts(3,14): error TS2339: Property 'toUpperCase' does not exist on type 'Date'.

Discriminated unions

This is the pattern to reach for. Give every member the same field with a different literal type, and a switch on that field narrows each branch:

app.ts
type Circle = { kind: "circle"; radius: number }
type Square = { kind: "square"; side: number }

type Shape = Circle | Square

function area(s: Shape) {
  switch (s.kind) {
    case "circle":
      return Math.PI * s.radius ** 2
    case "square":
      return s.side ** 2
  }
}

console.log(area({ kind: "square", side: 3 }))
Output$ npx tsc --noEmit app.ts$ echo $?0

radius is reachable only in the "circle" branch. Reading the wrong field is caught:

app.ts
type Circle = { kind: "circle"; radius: number }
type Square = { kind: "square"; side: number }

function area(s: Circle | Square) {
  if (s.kind === "circle") {
    return s.side
  }

  return 0
}
Output$ npx tsc --noEmit app.tsapp.ts(6,14): error TS2339: Property 'side' does not exist on type 'Circle'.

Exhaustiveness with never

Nothing is assignable to never, which turns a forgotten case into a compile error. Assign the value to a never where every case should already have returned:

app.ts
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }

function area(s: Shape) {
  switch (s.kind) {
    case "circle":
      return Math.PI * s.radius ** 2
    case "square":
      return s.side ** 2
    default: {
      const never: never = s
      return never
    }
  }
}

console.log(area({ kind: "square", side: 3 }))
Output$ npx tsc --noEmit app.ts$ echo $?0

Now add a third shape and forget its case. The default becomes reachable, so s is no longer never:

app.ts
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "triangle"; base: number; height: number }

function area(s: Shape) {
  switch (s.kind) {
    case "circle":
      return Math.PI * s.radius ** 2
    case "square":
      return s.side ** 2
    default: {
      const never: never = s
      return never
    }
  }
}
Output$ npx tsc --noEmit app.tsapp.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.

An annotated return type catches it too, but says much less:

app.ts
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "triangle"; base: number; height: number }

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":
      return Math.PI * s.radius ** 2
    case "square":
      return s.side ** 2
  }
}
Output$ npx tsc --noEmit app.tsapp.ts(6,26): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

Type predicates

Move a check into a function and the checker follows it, as long as the function is a single expression:

app.ts
function isString(v: unknown) {
  return typeof v === "string"
}

const v: unknown = "ada"

if (isString(v)) {
  console.log(v.toUpperCase())
}
Output$ npx tsc --noEmit app.ts$ echo $?0

Add a statement and the inference stops. The helper now returns a plain boolean, which narrows nothing:

app.ts
function isString(v: unknown) {
  const t = typeof v
  if (t === "number") return false
  return t === "string"
}

const v: unknown = "ada"

if (isString(v)) {
  console.log(v.toUpperCase())
}
Output$ npx tsc --noEmit app.tsapp.ts(10,15): error TS18046: 'v' is of type 'unknown'.

The fix is to say what the true result proves, with v is string:

app.ts
function isUser(v: unknown): v is { handle: string } {
  return typeof v === "object" && v !== null && "handle" in v
}

const data: unknown = JSON.parse('{"handle":"ada"}')

if (isUser(data)) {
  console.log(data.handle)
}
Output$ npx tsc --noEmit app.ts$ echo $?0

The same inference is why this works without any annotation — filter gives string[], not (string | null)[]:

app.ts
const xs: (string | null)[] = ["a", null]

const ys = xs.filter((v) => v !== null)

const check: string[] = ys
console.log(check)
Output$ npx tsc --noEmit app.ts$ echo $?0

Assertion functions

When the failure case should throw rather than branch, asserts v is User narrows everything after the call:

app.ts
type User = { handle: string }

function assertUser(v: unknown): asserts v is User {
  if (typeof v !== "object" || v === null || !("handle" in v)) {
    throw new Error("not a user")
  }
}

const data: unknown = JSON.parse('{"wrong":1}')

try {
  assertUser(data)
  console.log(data.handle)
} catch (err) {
  console.log((err as Error).message)
}
Output$ node app.tsnot a user

There is no if. The call either throws or data is a User from that line on.

app.ts
type User = { handle: string }

const assertUser = (v: unknown): asserts v is User => {
  if (typeof v !== "object") throw new Error("no")
}

const data: unknown = {}
assertUser(data)
console.log(data.handle)
Output$ npx tsc --noEmit app.tsapp.ts(8,1): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation.app.ts(9,13): error TS18046: 'data' is of type 'unknown'.

Where narrowing is lost

A property read does not stay narrowed inside a callback, because the object could change in between:

app.ts
type Box = { value: string | null }

function f(b: Box) {
  if (b.value !== null) {
    ;[1].forEach(() => {
      console.log(b.value.toUpperCase())
    })
  }
}
Output$ npx tsc --noEmit app.tsapp.ts(6,19): error TS18047: 'b.value' is possibly 'null'.

Copy it into a const first. A const cannot change, so the narrowing holds:

app.ts
type Box = { value: string | null }

function f(b: Box) {
  const value = b.value

  if (value !== null) {
    ;[1].forEach(() => {
      console.log(value.toUpperCase())
    })
  }
}

f({ value: "ada" })
Output$ npx tsc --noEmit app.ts$ echo $?0

A let captured by a callback loses it for the same reason:

app.ts
let v: string | null = "ada"

if (v !== null) {
  setTimeout(() => {
    console.log(v.toUpperCase())
  }, 0)
}
Output$ npx tsc --noEmit app.tsapp.ts(5,17): error TS18047: 'v' is possibly 'null'.

There is one case the checker misses. A function that reassigns the variable is not tracked, so this compiles clean and crashes:

app.ts
let v: string | null = "ada"

function reset() {
  v = null
}

if (v !== null) {
  reset()

  try {
    console.log(v.toUpperCase())
  } catch (err) {
    console.log((err as Error).message)
  }
}
Output$ npx tsc --noEmit app.ts$ node app.tsCannot read properties of null (reading 'toUpperCase')