Codectionary / Developer documentation / TypeScript

Narrowing Primitive Unions with typeof

A typeof test identifies JavaScript primitive categories and lets TypeScript narrow a union accordingly.

What it is and why to use it

A typeof test identifies JavaScript primitive categories and lets TypeScript narrow a union accordingly. It is useful when one parameter accepts two deliberate formats, such as a numeric quantity or a textual label, and each format needs a different operation.

Common mistakes and limitations

typeof null is "object", and typeof an array is also "object". A typeof object check does not establish a specific class or interface. Use the appropriate additional checks rather than asserting a shape prematurely.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

if (typeof value === "number") { /* numeric value */ }

Examples

Narrowing Primitive Unions with typeof

Standalone TypeScript 5.8+ example; expected output is explained below.

function format(value: number | string): string {
  if (typeof value === "number") return value.toFixed(1);
  return value.toUpperCase();
}
console.log(format(12));
console.log(format("ready"));
  1. The number branch can call the numeric toFixed method.
  2. After that branch returns, the remaining value is a string and supports toUpperCase.
  3. Each input has a deliberate presentation rule. The checks run in JavaScript; the annotations are erased.
  4. Expected output: 12.0 READY

Best practices

  • typeof null is "object", and typeof an array is also "object". A typeof object check does not establish a specific class or interface. Use the appropriate additional checks rather than asserting a shape prematurely.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading