0
0
Typescriptprogramming~5 mins

typeof type guards in Typescript

Choose your learning style9 modes available
Introduction

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.

When you have a variable that can hold different types like string or number.
When you want to run different code depending on whether a value is a number or a string.
When you want to avoid errors by making sure a value is the right type before using it.
When you receive input from users or external sources and need to check its type.
When you want to write safer code that adapts to different data types.
Syntax
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.

Examples
This checks if value is a string before running the code inside.
Typescript
if (typeof value === 'string') {
  console.log('It is a string');
}
This adds 10 only if num is a number.
Typescript
if (typeof num === 'number') {
  console.log(num + 10);
}
This runs different code depending on whether input is a boolean or not.
Typescript
if (typeof input === 'boolean') {
  console.log('Boolean value:', input);
} else {
  console.log('Not a boolean');
}
Sample Program

This function uses typeof type guards to check the type of value and print a message accordingly.

Typescript
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);
OutputSuccess
Important Notes

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.

Summary

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.