MediumUnion & Intersection💻 Output Question

Union type — in operator narrows to the correct variant

💡

Hint

The "in" type guard narrows a union by checking if a property exists. After "meow" in animal, TypeScript knows the value is the Cat variant because only Cat has meow. This works for both discriminated and non-discriminated unions.

What does this output?

// Simulate union type narrowing via 'in' operator
// type Animal = Cat | Dog
// Cat has meow(), Dog has bark()

function makeSound(animal) {
  if ('meow' in animal) {
    console.log('Cat says: ' + animal.meow());
  } else if ('bark' in animal) {
    console.log('Dog says: ' + animal.bark());
  } else {
    console.log('Unknown animal');
  }
}

const cat = { meow: () => 'meow', lives: 9 };
const dog = { bark: () => 'woof', breed: 'Labrador' };
const fish = { swim: () => 'splash' };

makeSound(cat);
makeSound(dog);
makeSound(fish);

Correct Output

Cat says: meow
Dog says: woof
Unknown animal

Why this output?

Explanation: "in" operator checks property existence at runtime. TypeScript uses the same pattern to narrow union types in conditional blocks.

Key Insight: The "in" type guard narrows a union by checking if a property exists. After "meow" in animal, TypeScript knows the value is the Cat variant because only Cat has meow. This works for both discriminated and non-discriminated unions.

More Union & Intersection Output Questions

MediumIntersection type — must satisfy all merged propertiesHardUnion narrowing exhaustion — never in the default case

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz