Sub topic 6
Narrowing with the `in` Operator
Prerequisites
This chapter assumes you know basic TypeScript syntax, object types, union types, and JavaScript control flow. For example, Fish | Bird means a value can be either a Fish or a Bird.
How the `in` operator narrows a union
The in operator checks whether a property exists on an object. TypeScript uses that check as evidence about which member of a union you have.
Suppose two object types have different methods:
type Fish = {
swim(): void;
};
type Bird = {
fly(): void;
};
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}
move({
swim() {
console.log("Swimming");
},
});
move({
fly() {
console.log("Flying");
},
});Before the if statement, animal has the type Fish | Bird, so TypeScript cannot safely call either method. In the true branch, "swim" in animal proves that animal has a swim property. TypeScript narrows the value to Fish. The else branch contains the remaining union member, Bird.
The property name can be stored in a variable when the variable has a suitable literal type:
function describe(animal: Fish | Bird): string {
const property = "swim";
if (property in animal) {
return "This animal can swim";
}
return "This animal can fly";
}What the check actually means
The check asks whether the property exists, including through the object's prototype chain. It does not check whether the property value is useful or callable.
For example, this object has a swim property whose value is undefined:
const unusualFish = {
swim: undefined,
};
console.log("swim" in unusualFish); // trueA type such as { swim?: () => void } also needs care. An optional property may be present or absent, so TypeScript can keep that type in both branches:
type Fish = {
swim?: () => void;
};
type Bird = {
fly(): void;
};
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim?.();
} else {
animal.fly();
}
}The optional call, animal.swim?.(), avoids calling the method when the property exists but contains undefined.
A value on the right side of in must be a non-null object at runtime. Do not use this check before validating unknown input:
function hasName(value: unknown): boolean {
return (
typeof value === "object" &&
value !== null &&
"name" in value
);
}The first two checks prevent a runtime error from evaluating "name" in value on null or a primitive.
Choosing property checks
Use in when union members have different properties and those properties identify the available behavior. If every variant has one common literal property such as kind, a discriminated union may communicate the model more clearly. For external data, remember that in only proves property existence. Check the property's type as well.
Exercise
Why does TypeScript allow animal.swim() inside the true branch of if ("swim" in animal) when animal starts as Fish | Bird?
Show answer
The check proves that the value has a swim property. Among the union members, that property identifies Fish, so TypeScript narrows animal to Fish in the true branch.