Bird
Raised Fist0
Typescriptprogramming~10 mins

The in operator narrowing in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - The in operator narrowing
Start with union type variable
↓
Use 'in' operator to check property
↓
If property exists
↓
Narrow type to subtype with that property
↓
Use narrowed type safely
↓
Else
↓
Narrow type to other subtype
↓
Use narrowed type safely
↓
End
Check if a property exists in an object to tell TypeScript which subtype it is, so you can use it safely.
Execution Sample
Typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
  if ('swim' in animal) {
    animal.swim();
  } else {
    animal.fly();
  }
}
This code uses 'in' to check if 'swim' is in animal, then calls swim or fly accordingly.
Execution Table
StepCondition'swim' in animalNarrowed TypeActionOutput
1animal = Fish { swim }trueFishCall animal.swim()swim() called
2animal = Bird { fly }falseBirdCall animal.fly()fly() called
3No more animalsN/AN/AExit functionEnd
💡 All union cases checked, function ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
animalFish | BirdFish (swim)Bird (fly)N/A
Key Moments - 3 Insights
Why does TypeScript allow calling animal.swim() only inside the 'if' block?
Because the 'in' operator check ('swim' in animal) narrows the type to Fish, so TypeScript knows animal has swim() there (see execution_table step 1).
What happens if you try to call animal.fly() inside the 'if' block?
TypeScript will give an error because inside the 'if' block animal is narrowed to Fish, which does not have fly() (see execution_table step 1).
Can the 'in' operator check be used with any property name?
Yes, but it only narrows the type if the property uniquely identifies one subtype in the union (see concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the narrowed type when 'swim' in animal is true?
ABird
BFish
CFish | Bird
DUnknown
💡 Hint
Check the 'Narrowed Type' column in execution_table row 1.
At which step does the function call animal.fly()?
AStep 1
BStep 3
CStep 2
DNever
💡 Hint
Look at the 'Action' column in execution_table row 2.
If the animal object had both 'swim' and 'fly' properties, what would the 'in' operator narrowing do?
ATypeScript cannot narrow because both properties exist
BNarrow to Bird only
CNarrow to Fish because 'swim' checked first
DNarrow to Fish only
💡 Hint
Think about how 'in' operator narrowing works when properties overlap.
Concept Snapshot
Use 'in' operator to check if a property exists in a union type.
If true, TypeScript narrows the variable to the subtype with that property.
This lets you safely access that property's methods or fields.
Else, it narrows to the other subtype(s).
Example: if ('swim' in animal) { animal.swim(); } else { animal.fly(); }
Full Transcript
This visual execution shows how TypeScript uses the 'in' operator to narrow union types. We start with a variable that can be Fish or Bird. We check if 'swim' is in the variable. If yes, TypeScript knows it's a Fish and lets us call swim(). If no, it must be a Bird, so we call fly(). The execution table shows each step with the condition, narrowed type, and action. The variable tracker shows how the variable's type changes after each check. Key moments clarify why narrowing works only inside the correct branches. The quiz tests understanding of narrowing and behavior when properties overlap.

Practice

(1/5)
1.

What does the in operator do in TypeScript?

easy
A. Adds a new property to an object
B. Checks if a property exists in an object and narrows the type
C. Deletes a property from an object
D. Checks if a value is equal to a property

Solution

  1. Step 1: Understand the in operator purpose

    The in operator checks if a given property exists in an object.
  2. Step 2: Recognize its use in TypeScript narrowing

    TypeScript uses this check to narrow the type safely based on the presence of the property.
  3. Final Answer:

    Checks if a property exists in an object and narrows the type -> Option B
  4. Quick Check:

    in operator = property check and type narrowing [OK]
Hint: Remember: in checks property presence to narrow types [OK]
Common Mistakes:
  • Thinking in adds or deletes properties
  • Confusing in with equality checks
  • Assuming in works only for arrays
2.

Which of the following is the correct syntax to check if property name exists in object obj using the in operator?

?
easy
A. "name" in obj
B. obj in "name"
C. obj.hasOwnProperty("name")
D. obj.name in

Solution

  1. Step 1: Recall the in operator syntax

    The correct syntax is: "propertyName" in object.
  2. Step 2: Match the syntax with options

    "name" in obj matches the correct syntax exactly: "name" in obj.
  3. Final Answer:

    "name" in obj -> Option A
  4. Quick Check:

    Syntax is "property" in object [OK]
Hint: Syntax is always "property" in object [OK]
Common Mistakes:
  • Reversing the order of property and object
  • Using method calls instead of in
  • Leaving in without operands
3.

What will be the output of the following TypeScript code?

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

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    return "Fish can swim";
  } else {
    return "Bird can fly";
  }
}

console.log(move({ swim: () => {} }));
medium
A. Type error at compile time
B. "Bird can fly"
C. "Fish can swim"
D. Runtime error

Solution

  1. Step 1: Analyze the input object

    The object passed has a swim method, so it matches the Fish type.
  2. Step 2: Check the in operator condition

    The condition "swim" in animal is true, so the function returns "Fish can swim".
  3. Final Answer:

    "Fish can swim" -> Option C
  4. Quick Check:

    Property "swim" exists, so output is "Fish can swim" [OK]
Hint: Check which property exists to decide output [OK]
Common Mistakes:
  • Confusing which property belongs to which type
  • Assuming both properties exist simultaneously
  • Expecting compile or runtime errors
4.

Identify the error in this TypeScript code using the in operator and fix it:

type Cat = { meow: () => void };
type Dog = { bark: () => void };

function speak(animal: Cat | Dog) {
  if (animal in "meow") {
    return "Cat speaks";
  } else {
    return "Dog speaks";
  }
}
medium
A. The in operator operands are reversed; should be "meow" in animal
B. Missing return type annotation
C. Function should use typeof instead of in
D. No error; code is correct

Solution

  1. Step 1: Check in operator syntax

    The syntax requires the property name as the left operand and the object as the right operand.
  2. Step 2: Identify the error in the code

    The code uses animal in "meow", which reverses operands. It should be "meow" in animal.
  3. Final Answer:

    The in operator operands are reversed; should be "meow" in animal -> Option A
  4. Quick Check:

    Property name must be left, object right in in [OK]
Hint: Remember: "property" in object, not object in "property" [OK]
Common Mistakes:
  • Swapping operands of the in operator
  • Using typeof instead of in for property checks
  • Ignoring TypeScript narrowing benefits
5.

Given the following types and function, what will describeAnimal return when called with { fly: () => {}, name: "Eagle" }?

type Fish = { swim: () => void };
type Bird = { fly: () => void; name: string };

function describeAnimal(animal: Fish | Bird) {
  if ("swim" in animal) {
    return "Fish";
  } else if ("name" in animal) {
    return `Bird named ${animal.name}`;
  } else {
    return "Unknown";
  }
}
hard
A. "Fish"
B. Type error because of missing property
C. "Unknown"
D. "Bird named Eagle"

Solution

  1. Step 1: Check the input object properties

    The object has fly and name properties, but no swim.
  2. Step 2: Evaluate the in operator conditions

    First condition "swim" in animal is false. Second condition "name" in animal is true, so it returns Bird named Eagle.
  3. Final Answer:

    "Bird named Eagle" -> Option D
  4. Quick Check:

    Property "name" exists, so output is "Bird named Eagle" [OK]
Hint: Check properties in order to find matching type [OK]
Common Mistakes:
  • Assuming presence of fly means Fish
  • Ignoring the second in check for name
  • Expecting errors due to missing swim
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard