JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Type Narrowing and Type Guards

9 min read ยท
In this lesson7

"In Jurassic Park, it's not enough to know you have a dinosaur in front of you," says Robert Muldoon, the park's chief game warden. "You need to know exactly WHETHER it's a predator, WHETHER it's a herbivore, WHETHER it flies, WHETHER it swims. The security protocol you activate depends on that. One wrong assumption and you have a catastrophe."

Type narrowing in TypeScript works similarly - it's the process of narrowing a broad type to a more specific one. When a variable has type string | number, TypeScript doesn't know whether it's text or a number. With type guards, we can "narrow" the type so the compiler knows exactly what it's dealing with. This is a fundamental technique for writing safe TypeScript code.

The typeof Operator as a Type Guard

The simplest type guard is typeof - a JavaScript operator that TypeScript understands and uses for type narrowing. When you check the type of a variable using typeof, the compiler automatically knows what type the variable has inside the if block.

// Function accepting different types of dinosaur data
function formatDinosaurData(value: string | number | boolean): string {
  if (typeof value === "string") {
    // TypeScript knows that value is of type string here
    return value.toUpperCase();
  }
  if (typeof value === "number") {
    // TypeScript knows that value is of type number here
    return value.toFixed(2) + " kg";
  }
  // TypeScript knows that value is of type boolean here
  return value ? "Active" : "Inactive";
}

console.log(formatDinosaurData("Tyrannosaurus Rex")); // "TYRANNOSAURUS REX"
console.log(formatDinosaurData(7500));                 // "7500.00 kg"
console.log(formatDinosaurData(true));                 // "Active"

In the above example, TypeScript automatically narrows the type of value in each if block. After checking typeof value === "string", the compiler knows that inside that block value is a string, so you can safely call .toUpperCase(). This works with types "string", "number", "boolean", "bigint", "symbol", "undefined", "object", and "function".

The instanceof Operator

When working with classes, instanceof allows you to check whether an object is an instance of a specific class. TypeScript automatically narrows the type after such a check.

class Carnivore {
  name: string;
  biteForce: number;

  constructor(name: string, biteForce: number) {
    this.name = name;
    this.biteForce = biteForce;
  }

  hunt(): string {
    return `${this.name} hunts with bite force of ${this.biteForce}N!`;
  }
}

class Herbivore {
  name: string;
  favoriteFood: string;

  constructor(name: string, favoriteFood: string) {
    this.name = name;
    this.favoriteFood = favoriteFood;
  }

  graze(): string {
    return `${this.name} calmly eats ${this.favoriteFood}`;
  }
}

// Function handling both dinosaur types
function handleDinosaur(dino: Carnivore | Herbivore): string {
  if (dino instanceof Carnivore) {
    // TypeScript knows that dino is Carnivore here
    return dino.hunt(); // We have access to hunt() and biteForce
  }
  // TypeScript knows that dino is Herbivore here
  return dino.graze(); // We have access to graze() and favoriteFood
}

const rex = new Carnivore("T-Rex", 12800);
const trike = new Herbivore("Triceratops", "ferns");

console.log(handleDinosaur(rex));   // "T-Rex hunts with bite force of 12800N!"
console.log(handleDinosaur(trike)); // "Triceratops calmly eats ferns"

The in Operator

The in operator checks whether an object has a given property. TypeScript uses this to narrow types in union types.

interface FlyingDinosaur {
  name: string;
  maxAltitude: number;
  wingspan: number;
}

interface SwimmingDinosaur {
  name: string;
  maxDepth: number;
  swimSpeed: number;
}

interface LandDinosaur {
  name: string;
  runSpeed: number;
  weight: number;
}

type Dinosaur = FlyingDinosaur | SwimmingDinosaur | LandDinosaur;

function describeDinosaur(dino: Dinosaur): string {
  if ("maxAltitude" in dino) {
    // TypeScript knows this is FlyingDinosaur
    return `${dino.name} flies up to altitude of ${dino.maxAltitude}m, wingspan: ${dino.wingspan}m`;
  }
  if ("maxDepth" in dino) {
    // TypeScript knows this is SwimmingDinosaur
    return `${dino.name} dives to ${dino.maxDepth}m, speed: ${dino.swimSpeed} km/h`;
  }
  // TypeScript knows this is LandDinosaur
  return `${dino.name} runs at speed of ${dino.runSpeed} km/h, weighs ${dino.weight} kg`;
}

const pteranodon: FlyingDinosaur = { name: "Pteranodon", maxAltitude: 500, wingspan: 7 };
const mosasaurus: SwimmingDinosaur = { name: "Mosasaurus", maxDepth: 200, swimSpeed: 48 };
const velociraptor: LandDinosaur = { name: "Velociraptor", runSpeed: 64, weight: 15 };

console.log(describeDinosaur(pteranodon));
console.log(describeDinosaur(mosasaurus));
console.log(describeDinosaur(velociraptor));

The in operator is particularly useful when working with interfaces (not classes), because instanceof only works with classes, while in simply checks for the presence of a property.

Custom Type Guard Functions (the is Keyword)

You can create your own type guard functions that return the special type parameterName is Type. This way TypeScript understands that after a positive check, the variable has a specific type.

interface DinoEgg {
  species: string;
  weight: number;
  incubationDays: number;
}

interface HatchedDino {
  species: string;
  weight: number;
  age: number;
  enclosureId: string;
}

// Custom type guard - function returns "specimen is HatchedDino"
function isHatched(specimen: DinoEgg | HatchedDino): specimen is HatchedDino {
  return "age" in specimen && "enclosureId" in specimen;
}

function processSpecimen(specimen: DinoEgg | HatchedDino): string {
  if (isHatched(specimen)) {
    // TypeScript knows that specimen is HatchedDino here
    return `${specimen.species} - age: ${specimen.age} days, enclosure: ${specimen.enclosureId}`;
  }
  // TypeScript knows that specimen is DinoEgg here
  return `Egg of ${specimen.species} - incubation: ${specimen.incubationDays} days`;
}

// More advanced type guard with validation
function isCarnivoreData(data: unknown): data is { species: string; biteForce: number; diet: "carnivore" } {
  return (
    typeof data === "object" &&
    data !== null &&
    "species" in data &&
    "biteForce" in data &&
    "diet" in data &&
    (data as any).diet === "carnivore"
  );
}

// Usage with an unknown data source (e.g., API)
function processParkData(rawData: unknown): string {
  if (isCarnivoreData(rawData)) {
    // TypeScript knows that rawData has the fields species, biteForce, diet
    return `Predator: ${rawData.species}, force: ${rawData.biteForce}N`;
  }
  return "Unknown data type";
}

console.log(processParkData({ species: "T-Rex", biteForce: 12800, diet: "carnivore" }));
console.log(processParkData({ name: "Triceratops" }));

Custom type guards are particularly useful when:

  1. The checking logic is complex and you want to extract it into a separate function
  2. You're working with data from external sources (API, JSON files), whose type is unknown
  3. You want to create reusable validation tools

Discriminated Unions and Exhaustive Checks

Discriminated unions is a pattern where each type in the union has a common "discriminating" field (tag) that uniquely identifies the type. TypeScript excels at narrowing types based on this field.

// Each type has a "kind" field as the discriminator
interface SecurityAlert {
  kind: "security";
  zone: string;
  threatLevel: number;
  dinosaurId: string;
}

interface MedicalAlert {
  kind: "medical";
  dinosaurId: string;
  symptoms: string[];
  veterinarianRequired: boolean;
}

interface SystemAlert {
  kind: "system";
  component: string;
  errorCode: number;
  message: string;
}

type ParkAlert = SecurityAlert | MedicalAlert | SystemAlert;

function handleAlert(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security":
      // TypeScript knows this is SecurityAlert
      return `SECURITY ALARM! Zone: ${alert.zone}, Threat: ${alert.threatLevel}/10, Dinosaur: ${alert.dinosaurId}`;
    case "medical":
      // TypeScript knows this is MedicalAlert
      return `MEDICAL ALERT! Dinosaur: ${alert.dinosaurId}, Symptoms: ${alert.symptoms.join(", ")}`;
    case "system":
      // TypeScript knows this is SystemAlert
      return `SYSTEM FAILURE! Component: ${alert.component}, Code: ${alert.errorCode}`;
  }
}

Exhaustive Check with the never Type

The never type in TypeScript means "a value that will never occur". We can use it to check whether we've handled ALL variants of a discriminated union. If we add a new variant and forget to handle it, TypeScript will throw a compilation error.

// Exhaustive check - TypeScript will warn us if we miss any variant
function handleAlertExhaustive(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security":
      return `Security: ${alert.zone}`;
    case "medical":
      return `Medical: ${alert.dinosaurId}`;
    case "system":
      return `System: ${alert.component}`;
    default:
      // If we add a new alert type and forget to handle it,
      // TypeScript will report an error, because alert won't be of type never
      const exhaustiveCheck: never = alert;
      return exhaustiveCheck;
  }
}

// Practical helper for exhaustive check
function assertNever(value: never, message: string = "Unhandled variant"): never {
  throw new Error(`${message}: ${JSON.stringify(value)}`);
}

Exhaustive check is a powerful technique - when you add e.g. WeatherAlert to the ParkAlert union, the compiler will IMMEDIATELY point out all places in the code where handling of the new variant is missing. It's like an early warning system in Jurassic Park - it doesn't let you overlook any threat.

Combining Type Guards - Practical Example

Below is a more elaborate example combining different type narrowing techniques in one system:

// Laboratory sample classification system
type SampleStatus = "collected" | "analyzing" | "completed" | "contaminated";

interface BaseSample {
  id: string;
  collectedAt: Date;
  status: SampleStatus;
}

interface DNASample extends BaseSample {
  type: "dna";
  species: string;
  purity: number;
  sequenceLength: number;
}

interface BloodSample extends BaseSample {
  type: "blood";
  species: string;
  volumeMl: number;
  pH: number;
}

interface FossilSample extends BaseSample {
  type: "fossil";
  era: string;
  estimatedAge: number;
}

type LabSample = DNASample | BloodSample | FossilSample;

// Custom type guard
function isDNASample(sample: LabSample): sample is DNASample {
  return sample.type === "dna";
}

// Checking status using typeof and custom guard
function canProcess(sample: LabSample): boolean {
  return sample.status === "collected" || sample.status === "analyzing";
}

// Main processing function - combines different techniques
function processLabSample(sample: LabSample): string {
  // Discriminated union narrowing
  switch (sample.type) {
    case "dna":
      if (sample.purity < 50) {
        return `DNA Sample ${sample.id}: purity too low (${sample.purity}%)`;
      }
      return `DNA Analysis ${sample.species}: ${sample.sequenceLength} base pairs, purity ${sample.purity}%`;

    case "blood":
      const phStatus = sample.pH >= 7.0 && sample.pH <= 7.6 ? "normal" : "OUT OF RANGE";
      return `Blood analysis ${sample.species}: ${sample.volumeMl}ml, pH ${sample.pH} (${phStatus})`;

    case "fossil":
      return `Fossil from era ${sample.era}: estimated age ${sample.estimatedAge} million years`;

    default:
      const _exhaustive: never = sample;
      return _exhaustive;
  }
}

// Test
const dnaSample: DNASample = {
  id: "DNA-042", type: "dna", collectedAt: new Date(),
  status: "collected", species: "Velociraptor", purity: 87, sequenceLength: 75000000
};

const bloodSample: BloodSample = {
  id: "BLD-015", type: "blood", collectedAt: new Date(),
  status: "analyzing", species: "Triceratops", volumeMl: 120, pH: 7.2
};

const fossilSample: FossilSample = {
  id: "FOS-003", type: "fossil", collectedAt: new Date(),
  status: "completed", era: "Cretaceous", estimatedAge: 68
};

console.log(processLabSample(dnaSample));
console.log(processLabSample(bloodSample));
console.log(processLabSample(fossilSample));

Summary

Type narrowing and type guards are fundamental TypeScript tools that allow you to write safe code while maintaining the flexibility of union types:

  1. typeof - narrows primitive types (string, number, boolean)
  2. instanceof - narrows class types
  3. in - narrows types based on the presence of a property in an object
  4. Custom type guards (is) - you define your own type-checking functions
  5. Discriminated unions - a shared "tag" field unambiguously identifies a variant
  6. Exhaustive check with never - the compiler ensures you've handled all variants

As Robert Muldoon says: "Species identification is the first step of the security protocol. Similarly, type narrowing is the first step to safe code - never assume what you're dealing with. Check, narrow the type, and act with confidence."

Code for this lesson: index.ts
// Type narrowing and type guards - Jurassic Park
console.log("=== TYPE NARROWING AND TYPE GUARDS ===\n");

// ===========================================
// 1. typeof - narrowing primitive types
// ===========================================

function formatDinoData(value: string | number | boolean): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  if (typeof value === "number") {
    return value.toFixed(2) + " kg";
  }
  return value ? "Active" : "Inactive";
}

console.log("--- typeof ---");
console.log(formatDinoData("Tyrannosaurus Rex"));
console.log(formatDinoData(7500));
console.log(formatDinoData(true));

// ===========================================
// 2. instanceof - narrowing classes
// ===========================================

class Carnivore {
  constructor(public name: string, public biteForce: number) {}
  hunt(): string { return `${this.name} hunts with a force of ${this.biteForce}N!`; }
}

class Herbivore {
  constructor(public name: string, public food: string) {}
  graze(): string { return `${this.name} eats ${this.food}`; }
}

function handleDino(dino: Carnivore | Herbivore): string {
  if (dino instanceof Carnivore) {
    return dino.hunt();
  }
  return dino.graze();
}

console.log("\n--- instanceof ---");
console.log(handleDino(new Carnivore("T-Rex", 12800)));
console.log(handleDino(new Herbivore("Triceratops", "ferns")));

// ===========================================
// 3. in - checking properties
// ===========================================

interface FlyingDino { name: string; maxAltitude: number; }
interface SwimmingDino { name: string; maxDepth: number; }
interface LandDino { name: string; runSpeed: number; }

type AnyDino = FlyingDino | SwimmingDino | LandDino;

function describeDino(dino: AnyDino): string {
  if ("maxAltitude" in dino) return `${dino.name} flies up to ${dino.maxAltitude}m`;
  if ("maxDepth" in dino) return `${dino.name} dives down to ${dino.maxDepth}m`;
  return `${dino.name} runs at ${dino.runSpeed} km/h`;
}

console.log("\n--- in operator ---");
console.log(describeDino({ name: "Pteranodon", maxAltitude: 500 }));
console.log(describeDino({ name: "Mosasaurus", maxDepth: 200 }));
console.log(describeDino({ name: "Velociraptor", runSpeed: 64 }));

// ===========================================
// 4. Custom type guard (is)
// ===========================================

interface DinoEgg { species: string; incubationDays: number; }
interface HatchedDino { species: string; age: number; enclosureId: string; }

function isHatched(s: DinoEgg | HatchedDino): s is HatchedDino {
  return "age" in s && "enclosureId" in s;
}

console.log("\n--- Custom type guard ---");
const egg: DinoEgg = { species: "Raptor", incubationDays: 45 };
const baby: HatchedDino = { species: "Raptor", age: 10, enclosureId: "E-01" };
console.log("Egg hatched?", isHatched(egg));
console.log("Baby hatched?", isHatched(baby));

// ===========================================
// 5. Discriminated union + exhaustive check
// ===========================================

interface SecurityAlert { kind: "security"; zone: string; level: number; }
interface MedicalAlert { kind: "medical"; dinoId: string; symptoms: string[]; }
interface SystemAlert { kind: "system"; component: string; errorCode: number; }

type ParkAlert = SecurityAlert | MedicalAlert | SystemAlert;

function handleAlert(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security": return `SECURITY: zone ${alert.zone}, level ${alert.level}`;
    case "medical": return `MEDICAL: dino ${alert.dinoId}, symptoms: ${alert.symptoms.join(", ")}`;
    case "system": return `SYSTEM: ${alert.component}, code ${alert.errorCode}`;
    default:
      const _never: never = alert;
      return _never;
  }
}

console.log("\n--- Discriminated union ---");
console.log(handleAlert({ kind: "security", zone: "A", level: 9 }));
console.log(handleAlert({ kind: "medical", dinoId: "D-01", symptoms: ["fever"] }));
console.log(handleAlert({ kind: "system", component: "Fence", errorCode: 500 }));

console.log("\nType narrowing = safe code with union types!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which operator allows narrowing a primitive type (e.g., string | number) in TypeScript?

Hands-on tasks in the game

  • Code editor

    Use typeof, instanceof, and the in operator to narrow types in the Jurassic Park system

  • Click in order

    Arrange the elements of a custom type guard function:

  1. QuestionThe typeof Operator as a Type Guard
  2. Coding taskType Narrowing - Practice
  3. Click in orderSorting: Custom Type Guard

Useful articles