The in operator helps check if an object has a specific property. It lets TypeScript know more about the object's type, so you can use it safely.
The in operator narrowing in Typescript
if ("propertyName" in object) { // code when property exists } else { // code when property does not exist }
The property name must be a string or a string literal.
This check narrows the type inside the if block, so you can safely use the property.
person has a name property before using it.if ("name" in person) { console.log(person.name); }
vehicle has speed. If yes, we print it; otherwise, we print a message.if ("speed" in vehicle) { console.log(vehicle.speed); } else { console.log("No speed property"); }
in to decide if animal can swim or fly, then calls the right method.type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}This program defines two pet types, Cat and Dog. The speak function uses the in operator to check which pet it got and calls the right sound.
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(pet: Cat | Dog) {
if ("meow" in pet) {
pet.meow();
} else {
pet.bark();
}
}
const myCat: Cat = { meow: () => console.log("Meow!") };
const myDog: Dog = { bark: () => console.log("Woof!") };
speak(myCat);
speak(myDog);The in operator only checks for property existence, not its value.
It works well with union types to help TypeScript understand which type you have.
Remember to use string literals for property names inside in.
The in operator checks if an object has a property.
It helps TypeScript narrow down types safely.
Use it to write safer code when working with objects that can be different types.
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
