Discover how a simple keyword can save you from confusing type checks and bugs!
Why The in operator narrowing in Typescript? - Purpose & Use Cases
Imagine you have an object that could be one of several types, each with different properties. You want to check which type it is by manually testing each property with if statements.
This manual checking is slow and error-prone because you have to write many conditions and remember all property names. It's easy to make mistakes or miss cases, leading to bugs.
The in operator narrowing lets TypeScript automatically understand which type an object is based on whether a property exists. This makes your code safer and easier to write.
if (obj.propA !== undefined) { /* treat as TypeA */ } else if (obj.propB !== undefined) { /* treat as TypeB */ }
if ('propA' in obj) { /* treat as TypeA */ } else if ('propB' in obj) { /* treat as TypeB */ }
This lets you write clear, concise code that safely handles different object shapes without extra checks or errors.
For example, when handling user input that could be from different form types, you can quickly check which form was submitted by testing for a unique property with in.
Manual property checks are slow and error-prone.
in operator narrowing lets TypeScript detect object types by property presence.
This makes code safer, clearer, and easier to maintain.
Practice
What does the in operator do in TypeScript?
Solution
Step 1: Understand the
Theinoperator purposeinoperator checks if a given property exists in an object.Step 2: Recognize its use in TypeScript narrowing
TypeScript uses this check to narrow the type safely based on the presence of the property.Final Answer:
Checks if a property exists in an object and narrows the type -> Option BQuick Check:
inoperator = property check and type narrowing [OK]
in checks property presence to narrow types [OK]- Thinking
inadds or deletes properties - Confusing
inwith equality checks - Assuming
inworks only for arrays
Which of the following is the correct syntax to check if property name exists in object obj using the in operator?
?
Solution
Step 1: Recall the
The correct syntax is:inoperator syntax"propertyName" in object.Step 2: Match the syntax with options
"name" in obj matches the correct syntax exactly:"name" in obj.Final Answer:
"name" in obj -> Option AQuick Check:
Syntax is "property" in object [OK]
- Reversing the order of property and object
- Using method calls instead of
in - Leaving
inwithout operands
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: () => {} }));Solution
Step 1: Analyze the input object
The object passed has aswimmethod, so it matches theFishtype.Step 2: Check the
The conditioninoperator condition"swim" in animalis true, so the function returns "Fish can swim".Final Answer:
"Fish can swim" -> Option CQuick Check:
Property "swim" exists, so output is "Fish can swim" [OK]
- Confusing which property belongs to which type
- Assuming both properties exist simultaneously
- Expecting compile or runtime errors
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";
}
}Solution
Step 1: Check
The syntax requires the property name as the left operand and the object as the right operand.inoperator syntaxStep 2: Identify the error in the code
The code usesanimal in "meow", which reverses operands. It should be"meow" in animal.Final Answer:
Theinoperator operands are reversed; should be "meow" in animal -> Option AQuick Check:
Property name must be left, object right inin[OK]
- Swapping operands of the
inoperator - Using
typeofinstead ofinfor property checks - Ignoring TypeScript narrowing benefits
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";
}
}Solution
Step 1: Check the input object properties
The object hasflyandnameproperties, but noswim.Step 2: Evaluate the
First conditioninoperator conditions"swim" in animalis false. Second condition"name" in animalis true, so it returnsBird named Eagle.Final Answer:
"Bird named Eagle" -> Option DQuick Check:
Property "name" exists, so output is "Bird named Eagle" [OK]
- Assuming presence of
flymeans Fish - Ignoring the second
incheck forname - Expecting errors due to missing
swim
Ready to prove it?
Pass the test and this pattern moves unknown
