I was sure it was working few versions back, TypeScript supported operator in to test existence of a field and narrowed/modified the type accordingly.
How to rewrite following code in a type-safe manner (e.g. no any)?
const t: object = Math.random() > 0.5 ? { x: 1 } : { y: true };
if ('y' in t && typeof t.y === 'boolean') {
console.log(t.y ? 'Y TRUE':'Y FALSE'); // error
} else if('x' in t) {
console.log('X =', t.x); // error
} else {
console.log('?', t);
}
All lines with field access of t are in red, TS compiler complaining that given field doesn't exist on type object, even though in both cases on the line before the in operator confirmed the field is present and thus the type should have been updated.
I also tried unknown (+ typeof ... === 'object'), that didn't work either.
tto: object. The inferred type ({ x: number; y?: undefined; } | { y: boolean; x?: undefined; }) is a union that can be discriminated with theintype guard: typescriptlang.org/play/…