Narrowing uncertain values

Narrow with typeof

Refine a primitive union by checking the runtime kind before using type-specific operations.

A union describes every allowed value at the boundary. A runtime check tells TypeScript which member exists on the current path:

function format(value: string | number) {
  return typeof value === 'number' ? value.toFixed(2) : value.trim()
}

Inside the first branch, value is a number. In the other branch, it must be a string. This is narrowing.

The check exists at runtime, and TypeScript follows its control flow. If you move the number operation before the check, the error returns.

Remember one JavaScript edge case: typeof null is 'object'. A check for an object usually also needs value !== null.

The union remains honest at the boundary, while each branch gets the operations it can safely use.

Exercise: extend the function to accept boolean. Add a branch that returns 'yes' or 'no', and hover over value in every branch.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →