Concept Flow - typeof type guards
Start with variable
Check typeof variable
Handle string
End
Check the type of a variable using typeof, then run code based on the type.
function printValue(x: string | number) { if (typeof x === 'string') { console.log('String:', x.toUpperCase()); } else { console.log('Number:', x.toFixed(2)); } }
| Step | Variable x | Condition | Condition Result | Branch Taken | Output |
|---|---|---|---|---|---|
| 1 | 'hello' | typeof x === 'string' | true | if branch | String: HELLO |
| 2 | 42 | typeof x === 'string' | false | else branch | Number: 42.00 |
| 3 | true | typeof x === 'string' | false | else branch | Number: Error (not handled) |
| Variable x | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| x | undefined | 'hello' | 42 | true |
typeof type guards check a variable's type at runtime.
Syntax: if (typeof x === 'string') { ... } else { ... }
Allows safe use of type-specific methods.
Common types: 'string', 'number', 'boolean', 'undefined', 'object', 'function'.
Use to avoid errors when handling union types.