0
0
Typescriptprogramming~5 mins

Why type narrowing is needed in Typescript

Choose your learning style9 modes available
Introduction

Type narrowing helps TypeScript understand exactly what kind of value you are working with. This makes your code safer and helps avoid mistakes.

When you have a variable that can hold different types and you want to do something specific for each type.
When you want to avoid errors by checking the type before using a value.
When you want to make your code easier to read and understand by clearly showing what type is expected.
When you want to use features or methods that only exist on certain types.
When you want TypeScript to give you helpful hints and warnings based on the exact type.
Syntax
Typescript
if (typeof variable === 'string') {
  // variable is treated as string here
} else if (typeof variable === 'number') {
  // variable is treated as number here
}
Type narrowing often uses checks like typeof, instanceof, or custom type guards.
Inside the blocks where the type is narrowed, TypeScript knows the exact type and allows only the correct operations.
Examples
This example narrows the type of x to string or number so you can safely use string or number methods.
Typescript
function printLength(x: string | number) {
  if (typeof x === 'string') {
    console.log(x.length);
  } else {
    console.log(x.toFixed(2));
  }
}
This example uses a custom type guard to narrow value to a Date type.
Typescript
function isDate(value: unknown): value is Date {
  return value instanceof Date;
}

function printDate(value: unknown) {
  if (isDate(value)) {
    console.log(value.toISOString());
  } else {
    console.log('Not a date');
  }
}
Sample Program

This program shows how type narrowing lets us handle different types safely and clearly.

Typescript
function describe(value: string | number | boolean) {
  if (typeof value === 'string') {
    console.log(`String with length ${value.length}`);
  } else if (typeof value === 'number') {
    console.log(`Number with fixed 2 decimals: ${value.toFixed(2)}`);
  } else {
    console.log(`Boolean value: ${value}`);
  }
}

describe('hello');
describe(3.14159);
describe(true);
OutputSuccess
Important Notes

Without type narrowing, TypeScript would not know which methods are safe to call.

Type narrowing helps catch bugs early by making sure you only use values in ways that make sense.

Summary

Type narrowing tells TypeScript the exact type of a variable at a certain point.

This makes your code safer and easier to understand.

Use type narrowing whenever you work with variables that can have multiple types.