我知道这听起来像是一个笼统的问题,但我无法在网上找到答案。
假设我有以下对象,
const myObject = {
property: {
subProperty: null
},
}
以下工作正常:const getValue = (): string => 'property'
const value = myObject[getValue() as keyof typeof myObject]
但是,当我尝试输入 subProperty
时值,出现错误。这是我尝试输入的方法:const getValue = (): string => 'property'
const getSubValue = (): string => 'subProperty'
const value = myObject[getValue() as keyof typeof myObject]
const subValue = myObject[getValue() as keyof typeof myObject][getSubValue() as keyof typeof myObject[getValue() as keyof typeof myObject]]
我知道我可以将这两种方法更改为以下内容:const getValue = (): 'property' => 'property'
const getSubValue = (): 'subProperty' => 'subProperty'
这将在没有 keyof typeof
的情况下工作指标,但显然我需要将两个函数的返回值保持为 string
.
最佳答案
TypeScript 解析器似乎无法处理表达式的复杂性。因此,如果您使用中间变量,它将起作用:
const value = myObject[getValue() as keyof typeof myObject]
const subValue = value[getSubValue() as keyof typeof value]
关于javascript - 如何键入嵌套对象的子属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68223867/