0
0
Typescriptprogramming~5 mins

Runtime type checking strategies in Typescript

Choose your learning style9 modes available
Introduction

Sometimes, we want to check the type of data while the program is running to avoid errors. This helps make sure the program works correctly with the right kind of data.

When receiving data from users or external sources like APIs.
When you want to make sure a function gets the right type of input before using it.
When debugging to find out what type of data is causing problems.
When working with dynamic data that can change during the program.
When you want to add extra safety checks beyond TypeScript's compile-time checks.
Syntax
Typescript
if (typeof variable === 'string') {
  // code for string
} else if (typeof variable === 'number') {
  // code for number
} else {
  // code for other types
}

Use typeof to check simple types like string, number, boolean.

For objects or arrays, use Array.isArray() or check properties manually.

Examples
Check if value is a string before using it.
Typescript
const value: unknown = 'hello';

if (typeof value === 'string') {
  console.log('It is a string:', value);
} else {
  console.log('Not a string');
}
Custom type guard function to check if a value is a number.
Typescript
function isNumber(value: unknown): value is number {
  return typeof value === 'number';
}

const input: unknown = 42;
if (isNumber(input)) {
  console.log('Number:', input);
} else {
  console.log('Not a number');
}
Check if data is an array before using array methods.
Typescript
const data: unknown = [1, 2, 3];

if (Array.isArray(data)) {
  console.log('It is an array with length:', data.length);
} else {
  console.log('Not an array');
}
Sample Program

This program checks the type of different values at runtime and prints a message based on the type.

Typescript
function checkType(value: unknown) {
  if (typeof value === 'string') {
    console.log(`String with length ${value.length}`);
  } else if (typeof value === 'number') {
    console.log(`Number with value ${value}`);
  } else if (Array.isArray(value)) {
    console.log(`Array with ${value.length} items`);
  } else {
    console.log('Unknown type');
  }
}

checkType('hello');
checkType(123);
checkType([1, 2, 3]);
checkType({});
OutputSuccess
Important Notes

Runtime checks add safety but can slow down the program if overused.

TypeScript types disappear when running the program, so runtime checks are needed for real-time safety.

Use custom type guard functions to keep code clean and reusable.

Summary

Runtime type checking helps catch wrong data types while the program runs.

Use typeof, Array.isArray(), and custom functions for checks.

It is useful when working with unknown or dynamic data sources.