Type narrowing helps your program understand what kind of value it is working with. Using typeof lets you check the type and write safer code.
0
0
Type narrowing with typeof in Typescript
Introduction
When you want to do different things based on whether a value is a number or a string.
When you receive input that could be many types and need to handle each type correctly.
When you want to avoid errors by making sure you only use methods that exist on the value's type.
Syntax
Typescript
if (typeof variable === 'typeName') { // code for this type }
The typeof operator returns a string like 'string', 'number', 'boolean', 'object', or 'undefined'.
Use triple equals === to compare the result of typeof for accuracy.
Examples
This checks if
value is a string, then safely calls a string method.Typescript
if (typeof value === 'string') { console.log(value.toUpperCase()); }
This checks if
input is a number, then adds 10 to it.Typescript
if (typeof input === 'number') { console.log(input + 10); }
This checks if
data is a boolean, then prints 'Yes' or 'No'.Typescript
if (typeof data === 'boolean') { console.log(data ? 'Yes' : 'No'); }
Sample Program
This program uses typeof to check the type of value. It then does something different for strings, numbers, and booleans.
Typescript
function printValue(value: string | number | boolean) { if (typeof value === 'string') { console.log(`String: ${value.toUpperCase()}`); } else if (typeof value === 'number') { console.log(`Number: ${value + 100}`); } else if (typeof value === 'boolean') { console.log(`Boolean: ${value ? 'True' : 'False'}`); } else { console.log('Unknown type'); } } printValue('hello'); printValue(42); printValue(false);
OutputSuccess
Important Notes
Type narrowing with typeof only works with primitive types like string, number, boolean, undefined, and symbol.
For objects or arrays, you need other ways to narrow types, like instanceof or custom checks.
Summary
Type narrowing helps your code know exactly what type it is working with.
Use typeof to check simple types like string, number, and boolean.
This makes your code safer and easier to understand.