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.
0
0
The in operator narrowing in Typescript
Introduction
When you have an object that could be one of several types and want to check which type it is.
When you want to safely access a property that might not exist on all types.
When you want to avoid errors by confirming a property exists before using it.
When you want clearer and safer code by letting TypeScript narrow down types.
When working with objects from external sources where properties might vary.
Syntax
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.
Examples
This checks if
person has a name property before using it.Typescript
if ("name" in person) { console.log(person.name); }
Here, we check if
vehicle has speed. If yes, we print it; otherwise, we print a message.Typescript
if ("speed" in vehicle) { console.log(vehicle.speed); } else { console.log("No speed property"); }
This function uses
in to decide if animal can swim or fly, then calls the right method.Typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}Sample Program
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.
Typescript
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);OutputSuccess
Important Notes
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.
Summary
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.