// TypeScript narrows the type inside each branch automatically
Note typeof works for: "string", "number", "boolean", "undefined", "symbol", "bigint", "function", "object". Note: typeof null === "object" - this is a famous JavaScript quirk that TypeScript inherits.
// keyof extracts property names; typeof extracts the type of a value
Note keyof works on types; typeof works on values. They are often combined: keyof typeof myObject gives you the union of property names of a runtime object. typeof only works with variables and properties, not with arbitrary expressions like function calls.
Note typeof null === "object" is a historic bug that will never be fixed. Use value === null for null checks. Arrays report as "object" -- use Array.isArray() instead.
Frequently asked questions
How does TypeScript handle typeof?
This task is covered in 2 stacks on this page: TypeScript, JavaScript. The "typeof Guard" snippet in TypeScript uses `if (typeof value === "string") { ... }`.
Which code does the TypeScript example use?
The "typeof Guard" snippet uses `if (typeof value === "string") { ... }`, from the Type Guards & Narrowing section of the TypeScript cheat sheet.
Which stacks cover "typeof" on this page?
TypeScript, JavaScript. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "typeof Guard": typeof works for: "string", "number", "boolean", "undefined", "symbol", "bigint", "function", "object". Note: typeof null === "object" - this is a famous JavaScript quirk that TypeScript inherits.