Sub topic 6
Narrowing with the in operator
This chapter covers how the in operator narrows a union by checking for a property. It assumes you can write TypeScript unions and type aliases, and that you know typeof and equality narrowing from earlier chapters. By the end you should know when in is the right tool, what it does to types that do not mention the property, and where it fails.
What the in operator does
In JavaScript, "key" in obj evaluates to true when obj has a property named key. The check covers own properties and properties inherited through the prototype chain. It returns true even when the property's value is undefined.
TypeScript treats this expression as a type guard. When the left side is a string literal and the right side is a union, the compiler filters the union by which members could have that property.
type Fish = { swim(): void };
type Bird = { fly(): void };
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}In the true branch, animal is Fish, because only Fish declares swim. In the else branch, animal is Bird, because the compiler removed Fish. No cast is needed.
How the compiler filters the union
For "prop" in x, where x has a union type, TypeScript sorts each member into one of three groups:
| Member declares `prop` | True branch | False branch |
|---|---|---|
| Required property | Kept | Removed |
| Optional property | Kept | Kept |
| Not declared | Removed | Kept |
The optional case matters. A member with prop?: T may or may not have the property at runtime, so the compiler cannot rule it out in either branch.
type Admin = { name: string; permissions: string[] };
type Guest = { name: string; permissions?: string[] };
type Visitor = { name: string };
function describe(user: Admin | Guest | Visitor): string {
if ("permissions" in user) {
// user: Admin | Guest
return `${user.name} has ${user.permissions?.length ?? 0} permissions`;
}
// user: Guest | Visitor
return `${user.name} has no permissions`;
}In the true branch, Visitor is removed. Admin and Guest remain, so permissions on Guest is still possibly undefined, and the code uses ?. for that reason. In the false branch, Admin is removed. Guest remains because its optional property might be absent.
Choosing in over other guards
The in operator suits unions of object types that have no shared literal tag and are not classes. Other tools fit other cases.
| Situation | Better guard | Column |
|---|---|---|
| Primitives such as `string \ | number` | `typeof` |
| Class instances | `instanceof` | |
| Object types sharing a literal `kind` field | Discriminated union (`switch` on the tag) | |
| Object types distinguished by which methods or fields exist | `in` | |
| Data of type `unknown` | A user-defined type guard, which may use `in` internally |
Two object types such as Fish and Bird in the example above are plain shapes. They are not classes, so instanceof cannot tell them apart. They have no tag, so a switch is not available. The in check is the natural fit.
If you control the types, adding a kind field and using a discriminated union is usually more robust. The in check depends on the property names staying distinct, and a later change can silently break that.
Narrowing when the property exists on every member
If every union member declares the property as required, in narrows nothing useful. The true branch keeps every member, and the false branch becomes never.
type A = { id: number; a: string };
type B = { id: number; b: string };
function check(value: A | B): void {
if ("id" in value) {
// value: A | B
} else {
// value: never
}
}Seeing never in a branch tells you the check is redundant for the declared types. Use a property that differs between the members instead.
Narrowing with in and unknown values
Since TypeScript 4.9, in also narrows values whose type is object or unknown (after you rule out primitives and null). The compiler adds the checked property to the type with the value unknown. You can then read the property and narrow it with typeof.
This is the basis of the guard that validates parsed data. The example below comes from the later chapter on narrowing unknown, and it is useful here because it shows in in its most common real-world role.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function show(input: unknown): string {
return isApiUser(input) ? input.name : "not a user";
}Each step does a specific job:
typeof value === "object"rules out strings, numbers, booleans,undefined, and functions. It still allowsnull.value !== nullremovesnull. Theinoperator throws aTypeErrorwhen its right side is not an object, so this guard also prevents a runtime crash."id" in valuenarrowsvaluetoobject & Record<"id", unknown>."name" in valueaddsnamethe same way.typeof value.id === "number"narrows theunknownproperty tonumber. The same applies toname.
Without the in checks, value.id would be a compile error, because object has no property id.
Common errors and gotchas
The operator throws on primitives
"x" in "hello" throws TypeError: Cannot use 'in' operator to search for 'x' in hello. TypeScript rejects this at compile time when the right operand has a primitive type. With unknown or a loose union, you must check typeof value === "object" and value !== null first.
The property name must be a literal for narrowing
Narrowing works when the left operand is a string literal, a literal type, or a unique symbol. A general string variable does not narrow.
type Fish = { swim(): void };
type Bird = { fly(): void };
function moveByName(animal: Fish | Bird, method: string): void {
if (method in animal) {
// animal is still Fish | Bird
}
}The compiler cannot know which property method names, so it keeps the whole union.
Inherited properties count
Because in includes the prototype chain, "toString" in obj is true for almost every object. Use a property name that is specific to your types. If you need to test only own properties, use Object.hasOwn(obj, "key"). That call does not narrow in the same way, so you would need a type predicate around it.
A present property can still hold undefined
"name" in user tells you that the key exists. It does not tell you the value is defined. An object created as { name: undefined } passes the check. If a type declares name?: string, the compiler keeps undefined in the type after the check, which is correct.
Subtype relationships can mislead
Narrowing by in assumes a value matches one of the declared members. Objects at runtime can have extra properties. A value typed as Fish might also have a fly method, if it came from a structurally wider object. Then "fly" in animal is true for a Fish. The compiler cannot see this. If your data may carry extra properties, prefer a discriminant tag or check the exact shape.
type Fish = { swim(): void };
type Bird = { fly(): void };
const duck = { swim() {}, fly() {} };
const asFish: Fish = duck; // allowed: duck has swim
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}
move(asFish); // takes the swim branch, which is fine hereThis particular call is safe, but the reverse mistake is possible. With "fly" in animal checked first, the same value takes the bird branch even though its declared type was Fish. Treat in as a check on shape, not on declared type.
Narrowing does not survive reassignment or callbacks
As with other guards, narrowing by in applies to the variable in the branch. A callback created inside the branch may lose it if the variable can be reassigned. Copy the value into a const first, as covered in the chapter on the limits of narrowing.
Combining in with other guards
You can chain in with other checks in one condition. The compiler narrows step by step through && and ||.
type Circle = { radius: number };
type Rect = { width: number; height: number };
function area(shape: Circle | Rect | null): number {
if (shape === null) {
return 0;
}
if ("radius" in shape) {
return Math.PI * shape.radius ** 2;
}
return shape.width * shape.height;
}The null check removes null first. After "radius" in shape returns in the true case, the remaining type is Rect, so width and height are available with no further checks. This is control flow narrowing at work: each early return shrinks the type for the code that follows.
Summary of the rules
"prop" in xkeeps union members that declarepropin the true branch, and members that do not declare it required in the false branch.- Optional properties keep a member in both branches.
- Narrowing needs a literal property name on the left.
- On
unknown, rule out non-objects andnullbefore usingin. - Prefer a discriminated union when you control the types and they can share a tag.
Exercise
Given type A = { a: string }, type B = { b: number }, and type C = { a?: string; c: boolean }, what is the type of x in the true branch and in the false branch of if ("a" in x) when x is A | B | C?
Show answer
In the true branch x is A | C, because A declares a as required and C declares it as optional, while B does not declare a. In the false branch x is B | C, because A is removed (its a is required) and C stays (its a is optional, so it may be absent at runtime).
Exercise
Why must a guard that uses "id" in value on an unknown input first check typeof value === "object" and value !== null?
Show answer
The in operator throws a TypeError at runtime when its right operand is not an object, and typeof null is "object". The typeof check rules out primitives, and the null check rules out null. TypeScript also requires the right operand to be of an object type before it allows the in expression.