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.typeof operator do in TypeScript when used as a type guard?typeoftypeof operator checks the actual type of a value at runtime, like 'string' or 'number'.typeof in an if condition helps TypeScript know the exact type inside that block, making code safer.typeof as a type guard in TypeScript?=== is required to compare typeof result with a string.function checkValue(x: string | number) {
if (typeof x === 'string') {
return x.toUpperCase();
} else {
return x.toFixed(2);
}
}
console.log(checkValue(3.14159));toFixed(2) on the number, which returns a string with 2 decimals: '3.14'.typeof type guard:function process(value: string | boolean) {
if (typeof value === 'boolean') {
return value.toUpperCase();
} else {
return value;
}
}value is a boolean.toUpperCase(), which exists only on strings, not booleans, causing an error.string, number, or boolean using typeof type guards?function formatValue(val: string | number | boolean) {
// Fill in the blanks
}typeof val === 'string', 'number', and 'boolean' to safely handle each type.Pass the test and this pattern moves unknown