in Operator with Index Signatures
What you'll learn: How the in operator interacts with index signatures and why TypeScript sometimes can't narrow types when checking dynamic keys.
The Core Problem
You've learned that the in operator narrows types by checking if a property exists on an object. But what happens when you use in with objects that have index signatures—those flexible types that accept any string or number key?
An index signature looks like [key: string]: SomeType and means "this object can have any property name." The catch: when TypeScript sees in with an index signature, it often cannot narrow the type because the property might exist at runtime, even if TypeScript doesn't know about it statically.
How It Behaves
type StringRecord = {
[key: string]: string;
};
function process(obj: StringRecord | number[]) {
if ("length" in obj) {
// TypeScript CANNOT narrow here!
// Both types could have 'length'
// obj is still: StringRecord | number[]
}
}
Why? Because StringRecord accepts any string key via its index signature. TypeScript can't prove "length" is definitely not in StringRecord, so it can't eliminate that possibility.
When Narrowing Works
Narrowing does work when checking properties that definitely don't exist on one side:
if ("push" in obj) {
// If StringRecord had NO array methods in its signature
// This might narrow to number[]
// But it depends on what the index signature allows
}
Key Takeaway: The in operator cannot reliably narrow types when one side has an index signature accepting arbitrary keys, because TypeScript cannot prove the property doesn't exist dynamically.