The typeof Operator
Bridging the gap between JavaScript values and TypeScript types.
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.
"object"id: number;
}
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.
Remember this
- JavaScript
typeofruns at runtime (Value Space) and returns strings like"object". - TypeScript
typeofruns at compile-time (Type Space) and extracts exact type shapes. - Use
typeofto 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.