Bird
Raised Fist0
Typescriptprogramming~20 mins

The in operator narrowing in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
In Operator Narrowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of type narrowing with 'in' operator
What is the output of this TypeScript code when run with Node.js (ignoring type errors)?
Typescript
type Fish = { swim: () => string };
type Bird = { fly: () => string };

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

const fish: Fish = { swim: () => "Swimming" };
const bird: Bird = { fly: () => "Flying" };

console.log(move(fish));
console.log(move(bird));
ARuntime error: animal.swim is not a function
B"Flying" followed by "Swimming"
C"Swimming" followed by "Flying"
DCompilation error due to type mismatch
Attempts:
2 left
💡 Hint
The 'in' operator checks if a property exists on the object, helping TypeScript narrow the type.
🧠 Conceptual
intermediate
2:00remaining
Understanding 'in' operator narrowing with optional properties
Given the types below, which statement about the 'in' operator narrowing is true?
Typescript
type A = { x?: number };
type B = { y: string };

function test(obj: A | B) {
  if ('x' in obj) {
    // What can we say about obj here?
  }
}
AInside the if block, obj is narrowed to type A, but 'x' may still be undefined.
BInside the if block, obj is guaranteed to have property 'x' defined and not undefined.
CInside the if block, obj is narrowed to type B because 'x' is optional.
DThe 'in' operator cannot be used to narrow types with optional properties.
Attempts:
2 left
💡 Hint
The 'in' operator checks if the property exists, but optional properties may be undefined.
🔧 Debug
advanced
2:00remaining
Why does this 'in' operator narrowing fail?
Consider this TypeScript code snippet. Why does the compiler complain about accessing 'fly'?
Typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };

function move(animal: Fish | Bird) {
  if ('swim' in animal) {
    animal.fly();
  } else {
    animal.swim();
  }
}
ABecause 'fly' is not a property of Fish, the 'in' operator narrows animal to Bird, so animal.fly() is valid.
BThe compiler complains because 'fly' is not guaranteed to exist on animal even after the 'in' check.
CThe 'in' operator does not narrow union types when the property is not common to all types.
DThe compiler error occurs because 'swim' is missing in the else block.
Attempts:
2 left
💡 Hint
Check how TypeScript narrows types with the 'in' operator and property existence.
📝 Syntax
advanced
2:00remaining
Which option correctly uses 'in' operator for narrowing?
Which of the following TypeScript code snippets correctly narrows the type using the 'in' operator?
Aif ('swim' in animal) { animal.swim(); } else { animal.fly(); }
Bif (animal in 'swim') { animal.swim(); } else { animal.fly(); }
Cif ('swim' of animal) { animal.swim(); } else { animal.fly(); }
Dif ('swim' on animal) { animal.swim(); } else { animal.fly(); }
Attempts:
2 left
💡 Hint
Remember the correct syntax for the 'in' operator in TypeScript and JavaScript.
🚀 Application
expert
2:00remaining
Determine the number of keys in the narrowed object
Given the following TypeScript code, how many keys does the object 'obj' have inside the if block?
Typescript
type A = { a: number };
type B = { b: string };

function check(obj: A | B) {
  if ('a' in obj) {
    return Object.keys(obj).length;
  }
  return 0;
}

const result = check({ a: 1, extra: true } as A & { extra: boolean });
A0
B1
C3
D2
Attempts:
2 left
💡 Hint
Consider how Object.keys counts enumerable own properties regardless of type narrowing.

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