TypeScript中与"in"运算符相关的类型推理是否停止工作



我确信它在几个版本前就可以工作了,TypeScript支持运算符in来测试字段的存在性,并相应地缩小/修改了类型。

如何以类型安全的方式重写以下代码(例如,没有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);
}

字段访问为t的所有行都是红色的,TS编译器抱怨类型对象上不存在给定字段,尽管在这两种情况下,在in运算符确认字段存在之前,行上都存在字段,因此类型应该已经更新。

我还尝试了unknown(+typeof ... === 'object'(,但也不起作用。

属性xyobject类型中丢失,因此typescript会抱怨。

您需要定义自定义类型:

type ExAndWhy = {
x?: number;
y?: boolean;
}
const t: ExAndWhy = Math.random() > 0.5 ? { x: 1 } : { y: true };

如果您正在寻找";对象";可以容纳任何东西的类型,它是这样的:

type Anything = {
[key: string]: any;
};
const t:Anything = { x: 1, y: true};

相关内容

最新更新