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.