typeof typeof Narrowing
Last updated: 2026-10-22
typeof typeof Narrowing
The typeof guard is the most common type guard: at runtime typeof returns a type string for the value, and TypeScript narrows the union accordingly. After typeof value === "string", value is treated as a string and string methods are safe to call.
| Group | Narrowing & Assertions |
|---|---|
| Kind | Operator |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
function toNumber(value: string | number): number {
if (typeof value === "string") {
return Number(value); // value: string here
}
return value; // value: number here
}
⚙️ Parameters
| typeof value | Evaluated at runtime; returns one of eight strings: "string" / "number" / "boolean" / "object" / "function" / "undefined" / "symbol" / "bigint" |
|---|
Returns:The typeof expression itself yields a type string; the narrowing effect happens at compile time — within the branch the variable's type becomes the matching concrete type.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
string of length 5
number, doubled = 42
boolean: off
(Runtime output after transpilation; value.length and value * 2 type-check inside each case because typeof narrowing is in effect — narrowing is guaranteed statically by tsc, at runtime there are only values)
💡 Notes
ℹ️ Info typeof null === "object" is a historical JS quirk. TypeScript handles it built-in: after a typeof check the null case is narrowed correctly and never leaks into the "object" branch.
⚠️ Note typeof cannot tell arrays from plain objects — both are "object". Use Array.isArray(x) for arrays, and in or discriminated unions to tell object shapes apart.
💡 Tip typeof has two identities: in value position it is the runtime operator; in type position it is a type operator (type T = typeof someVar). This entry covers the narrowing use of the former.
🏷️ Related Narrowing & Assertions
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Why does an array stay "object" after a typeof check?
A Arrays are objects in JS, so typeof returns "object" for them. TypeScript ships Array.isArray() as the dedicated guard for arrays — that is the right tool for unions like string | number[].
Q Is switch (typeof value) different from a chain of ifs?
A Narrowing is identical — TS recognizes both guard forms. switch reads better with 3+ branches and pairs with exhaustiveness checking (never in default) to catch missing branches.
Q Can typeof value === "string" throw at runtime?
A No. typeof is one of the few operators safe on any expression — even an undeclared variable just yields "undefined". That safety is exactly why it works so well as a type guard.