TypeScript在对未知变量进行类型检查后仍然会触发错误ts2571



例如,以下将导致Object is of type 'unknown'.错误:

let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Maybe anything of the same shape
let key = "hello"; // Maybe any key of obj
if (Array.isArray(obj[key])) obj[key][1] = obj[key][0];

let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Maybe anything of the same shape
let key = "hello"; // Maybe any key of obj
let array = obj[key];
if (Array.isArray(array)) array[1] = array[0];

这是一个异常的行为(或可能是一个bug)?


好的,我能想到的一个原因是getter每次返回不同的值

const values = ["hello", 16, true];
let obj: {x: number, [key: string]: unknown} = {
x: 0,
get y() {
return values[this.x = (this.x + 1) % values.length];
}
};

这值得关注吗?

是的,这是当前TypeScript版本中预期的行为,它应该在TypeScript 4.4中变得更好——参见"别名条件和判别符的控制流分析"一节中的例子;在TS 4.4 RC blogpost.

最新更新