0Pricing
Frontend Academy · Lesson

Narrowing: typeof instanceof discriminated unions

Use type guards to narrow union types at runtime with typeof, instanceof, and discriminated union patterns.

What Is Type Narrowing?

TypeScript starts with a wide type (e.g., string | number). Narrowing is the process of refining the type to a more specific one inside a conditional block. TypeScript tracks narrowing automatically.

typeof Narrowing

The typeof operator narrows primitives. Inside an if block, TypeScript knows the exact type.

function format(value: string | number | boolean): string {
  if (typeof value === 'string') {
    return value.toUpperCase(); // string here
  }
  if (typeof value === 'number') {
    return value.toFixed(2);   // number here
  }
  return String(value);        // boolean here
}

All lessons in this course

  1. Generics: T extends and constraints
  2. Utility Types: Partial Required Pick Omit
  3. Mapped Types and Conditional Types
  4. Narrowing: typeof instanceof discriminated unions
← Back to Frontend Academy