Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)

28%
TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)

How do Type Narrowing and Custom Type Guards (`is`) work?

junior LevelCode ExampleTypeScript

In Simple Words: TypeScript automatically narrows types within conditional branches using:

  • typeof x === 'string'
  • x instanceof Date
  • 'property' in obj

When checking complex runtime objects, you write a User-Defined Type Guard returning arg is TargetType:

typescript
interface Fish { swim: () => void; }
interface Bird { fly: () => void; }

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim(); // TS guarantees pet is Fish here
  } else {
    pet.fly();  // TS guarantees pet is Bird here
  }
}