Typeof guards
Concept and syntax
typeof examines a JavaScript value at runtime. Inside a matching branch the checker excludes incompatible primitive types. It is useful for unknown input or primitive unions, but typeof null is "object" and arrays also report "object"; it is not a detailed object validator.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function format(x:string|number){ return typeof x === "number" ? x.toFixed(1) : x.toUpperCase(); }console.log(format(3),format("tea"));Expected output:
3.0 TEACommon mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2339. toFixed belongs to number. Guard that branch with typeof.
Practice and recap
Extend format to boolean and handle it explicitly.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typeof guards — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function format(x:string|number){ return typeof x === "number" ? x.toFixed(1) : x.toUpperCase(); }console.log(format(3),format("tea"));Which diagnostic and explanation match the rejected example under the lesson settings?
function format(x:string|number){ return x.toFixed(1); }