We use typeof type guards to check the type of a value at runtime. This helps TypeScript understand what kind of data we are working with so it can avoid mistakes.
typeof type guards in Typescript
if (typeof variable === 'type') { // code for this type } else { // code for other types }
The typeof operator returns a string like 'string', 'number', 'boolean', 'object', 'undefined', or 'function'.
Use triple equals === to compare the result of typeof to a string.
value is a string before running the code inside.if (typeof value === 'string') { console.log('It is a string'); }
num is a number.if (typeof num === 'number') { console.log(num + 10); }
input is a boolean or not.if (typeof input === 'boolean') { console.log('Boolean value:', input); } else { console.log('Not a boolean'); }
This function uses typeof type guards to check the type of value and print a message accordingly.
function printValue(value: string | number | boolean) { if (typeof value === 'string') { console.log(`String: ${value}`); } else if (typeof value === 'number') { console.log(`Number: ${value}`); } else if (typeof value === 'boolean') { console.log(`Boolean: ${value}`); } else { console.log('Unknown type'); } } printValue('hello'); printValue(42); printValue(true);
typeof works well for primitive types like string, number, and boolean.
It does not distinguish between different object types (like arrays or null), so use other checks for those.
Always use === to compare the result of typeof to avoid unexpected bugs.
typeof type guards help check the type of a value at runtime.
They make your code safer by letting TypeScript know the exact type inside a condition.
Use them when your variable can hold different primitive types like string, number, or boolean.
Practice
typeof operator do in TypeScript when used as a type guard?Solution
Step 1: Understand the purpose of
Thetypeoftypeofoperator checks the actual type of a value at runtime, like 'string' or 'number'.Step 2: Recognize its use as a type guard
Usingtypeofin an if condition helps TypeScript know the exact type inside that block, making code safer.Final Answer:
It checks the runtime type of a variable to narrow its type inside a condition. -> Option CQuick Check:
typeof narrows type [OK]
- Thinking typeof changes the variable's type
- Confusing typeof with type declarations
- Assuming typeof works at compile time only
typeof as a type guard in TypeScript?Solution
Step 1: Check the correct comparison operator
The strict equality operator===is required to comparetypeofresult with a string.Step 2: Verify the string literal format
The type name must be a string literal like 'string', 'number', etc., inside quotes.Final Answer:
if (typeof x === 'string') { /* code */ } -> Option AQuick Check:
Correct typeof syntax uses === and quotes [OK]
- Using single = instead of ===
- Not putting type name in quotes
- Using == instead of ===
function checkValue(x: string | number) {
if (typeof x === 'string') {
return x.toUpperCase();
} else {
return x.toFixed(2);
}
}
console.log(checkValue(3.14159));Solution
Step 1: Identify the type of input
The input is 3.14159, which is a number, so the else block runs.Step 2: Understand the else block behavior
The else block callstoFixed(2)on the number, which returns a string with 2 decimals: '3.14'.Final Answer:
'3.14' as a string with two decimals -> Option DQuick Check:
Number input uses toFixed(2) = '3.14' [OK]
- Thinking toFixed returns a number
- Confusing string and number outputs
- Ignoring the else block
typeof type guard:function process(value: string | boolean) {
if (typeof value === 'boolean') {
return value.toUpperCase();
} else {
return value;
}
}Solution
Step 1: Analyze the typeof condition
The condition checks ifvalueis a boolean.Step 2: Check method call on boolean
Inside the if block, it callstoUpperCase(), which exists only on strings, not booleans, causing an error.Final Answer:
Calling toUpperCase() on a boolean value causes an error. -> Option BQuick Check:
toUpperCase() invalid on boolean [OK]
- Assuming booleans have string methods
- Mixing up type guard conditions
- Ignoring method compatibility
string, number, or boolean using typeof type guards?function formatValue(val: string | number | boolean) {
// Fill in the blanks
}Solution
Step 1: Recognize multiple possible types
The variable can be string, number, or boolean, so each needs separate handling.Step 2: Use multiple typeof checks
Use if-else if blocks checkingtypeof val === 'string','number', and'boolean'to safely handle each type.Final Answer:
Use separate if blocks: if typeof val === 'string', else if 'number', else if 'boolean', then handle each accordingly. -> Option AQuick Check:
Multiple typeof checks for multiple types [OK]
- Handling all types as strings blindly
- Using typeof 'object' for primitives
- Skipping boolean type handling
Ready to prove it?
Pass the test and this pattern moves unknown
