从Object.entries中的条件键推断值的类型



假设这个JavaScript树对象具有这种类型和形状

type Tree = { [key: string]: number | Tree } & { SIZE: number }
// example
const tree: Tree = {
a: {
b: 1,
SIZE: 1
},
c: 2,
SIZE: 3
}

TypeScript可以很好地推断出tree[key]的类型是number

let total = 0
for (const [key, value] of Object.entries(tree)) {
if (key === 'SIZE') {
total += tree[key]
}
}

但不能推断出这里的value也是number的类型?

let total = 0
for (const [key, value] of Object.entries(tree)) {
if (key === 'SIZE') {
total += value    // Operator '+=' cannot be applied to types 'number' and 'number | Tree'.(2365)
}
}

在if语句中tree[key]value不应该是等价的吗?

我是否错误地定义了树的类型,或者是否有其他简单的方法可以让TypeScript推断类型?我宁愿不使用类型转换。

在第二个例子中,TypeScript无法推断出value是一个数字,因为你没有使用任何需要它是数字的操作。相反,TypeScript将值的类型推断为联合类型number | Tree,因为这是tree对象中值的类型。

最新更新