liveBook · Manning

Typeof operator

As explained in Essential TypeScript 5, Third Edition

The typeof operator is a JavaScript operator that produces a string identifying the type category of a value.

The typeof operator produces a string identifying a value’s JavaScript type category. It is useful when checking what a dynamically typed variable currently contains. section 3.3.1 section 7.2

Inspecting a changing variable

let myVar; console.log(`${myVar} = ${typeof myVar}`); myVar = 12; console.log(`${myVar} = ${typeof myVar}`); myVar = "Hello"; console.log(`${myVar} = ${typeof myVar}`); myVar = true; console.log(`${myVar} = ${typeof myVar}`); This produces undefined = undefined, 12 = number, Hello = string, and true = boolean. The reported type changes because the value changes.

Use the result as a runtime string, while keeping these boundaries in mind:

  • An unassigned variable produces undefined, which distinguishes it from assigned values. section 7.2
  • typeof null produces object, a longstanding compatibility oddity rather than a precise null classification. section 3.3.1
  • In TypeScript, typeof can serve as an alternative to a type assertion for JavaScript primitive types. section 7.8

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Demonstrates primitive results and the null exception, but stops short of broader object and function-type behavior.
Examples
Uses index.js and index.ts listings that inspect strings, numbers, booleans, undefined, and a changing variable.
What it assumes
Assumes familiarity with JavaScript values and variables while establishing that values, rather than variables, have types.
What you can do after
Diagnose/debug with it by checking a value’s runtime category and spotting unexpected assignments before calculations fail.
How it connects
Connects dynamic typing, primitive data types, type assertions, type unions, and strictNullChecks.

Also explained in

Compare how 3 books explain typeof operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.