The typeof Operator

Bridging the gap between JavaScript values and TypeScript types.

TypeScript3 min readConcept 12 of 54

Two worlds: Values and Types

JavaScript has a typeof operator that runs at runtime and returns a string (e.g. typeof 42 === "number").

TypeScript *also* has a typeof operator, but it runs entirely during compilation in the 'Type Space'. It takes a JavaScript variable and extracts its exact TypeScript shape.

Don't Repeat Yourself (DRY)

Often you have a complex configuration object or a default state object. Instead of manually writing an interface that exactly matches that object, you can just let TypeScript infer the type from the object itself using typeof.

This ensures your types always stay in perfect sync with your actual data.

Using typeof in Type Space

When you use typeof on the right side of a type declaration, you are in Type Space:

typescript const defaultTheme = { colors: { primary: "blue" }, spacing: 8 }; // Extracts the exact shape of defaultTheme type Theme = typeof defaultTheme; const myTheme: Theme = { colors: { primary: "red" }, spacing: 16 };

Try it

Watch how typeof behaves differently depending on whether it's executed in the JavaScript Runtime or the TypeScript Compiler.

const data = { id: 1 };

// 1. JavaScript (Value Space)
const jsResult = typeof data;

// 2. TypeScript (Type Space)
type TsResult = typeof data;
JS Runtime
"object"
Returns a basic string type.
TS Compiler
{
  id: number;
}
Extracts the exact shape.
TypeScript overloads typeof to do deep structural analysis.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the difference between JavaScript's typeof and TypeScript's typeof?

Remember this

  • JavaScript typeof runs at runtime (Value Space) and returns strings like "object".
  • TypeScript typeof runs at compile-time (Type Space) and extracts exact type shapes.
  • Use typeof to derive types from existing configuration objects or default values to stay DRY.
  • You cannot use a variable directly as a type; you must use typeof variable.

Done with this concept?

Mark it complete to track your progress. No login needed.