简体   繁体   English

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

[英]Infer type of value from conditional key in Object.entries

Say I have this JavaScript tree object with this type and shape假设我有这个类型和形状的 JavaScript 树对象

type Tree = { [key: string]: number | Tree } & { SIZE: number }

// example
const tree: Tree = {
  a: {
    b: 1,
    SIZE: 1
  },
  c: 2,
  SIZE: 3
}

TypeScript manages without problem to infer that the type of tree[key] is number here TypeScript 可以毫无问题地推断出tree[key]的类型是number here

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

But can't infer that the type of value is also number here?但是不能在这里推断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)
  }
}

Shouldn't tree[key] and value be equivalent inside the if-statement?在 if 语句中tree[key]value不应该是等价的吗?

Have I defined the type of my tree wrong or is there any other simple way that I can make TypeScript infer the type?我是否错误地定义了我的树的类型,或者是否有任何其他简单的方法可以让 TypeScript 推断类型? I'd rather not use type-casting.我宁愿不使用类型转换。

In the second example, TypeScript is unable to infer that value is a number because you are not using any operations that would require it to be a number.在第二个示例中,TypeScript 无法推断该value是一个数字,因为您没有使用任何要求它是一个数字的操作。 Instead, TypeScript infers the type of value to be the union type number | Tree相反,TypeScript 将值的类型推断为联合类型number | Tree number | Tree , because that is the type of the values in the tree object. number | Tree ,因为那是tree对象中值的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM