简体   繁体   English

如何在 typescript 中使用带变量的可选链接运算符

[英]How to use optional chaining operator with variable in typescript

I have following code and I would like to pass number from value key of variable object, How can I use variable for optional chaining operator for it to solve the error Element implicitly has an any type?我有以下代码,我想从变量 object 的值键中传递数字,如何将变量用于可选链接运算符来解决错误元素隐式具有any类型?

    function fun(i?: number) {
        console.log(i)
    }

    const variable = { min: { value: 1, name: 'google' }, max: {value: 2, name: 'apple'} }
    const variable2 = { min: { value: 1, name: 'google' } }
    const variable3 = { max: {value: 2, name: 'apple'} }

    fun(variable?.min.value) // working => 1
    fun(variable?.max.value) // working => 2
    fun(variable2?.min.value) // working => 1
    fun(variable2?.max.value) // working => undefined
    fun(variable3?.min.value) // working => undefined
    fun(variable3?.max.value) // working => 2

    Object.keys(variable).forEach((key) => {
        fun(variable?.[key]?.value) // working but with error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ min: { value: number; name: string; }; max: { value: number; name: string; }; }'.
    })

This isn't actually an optional chaining problem, but a problem with how Object.keys works.这实际上不是可选链接问题,而是Object.keys工作方式的问题。 Typescript assumes that an object may have more keys than is known at compile time so the type of key here is string and not keyof variable . Typescript 假定 object 可能具有比编译时已知的更多的键,因此这里的key类型是string而不是keyof variable To get around that you would have to let the TS compiler know that all the keys are known at compile time using为了解决这个问题,您必须让 TS 编译器知道所有键在编译时都是已知的,使用

Object.keys(variable).forEach((key) => {
  fun(variable[key as keyof typeof variable].value) 
})

You're already treating variable as a non-null variable when you use it in Object.keys so there's no need to additionally use optional chaining on it.当您在Object.keys中使用变量时,您已经将variable视为非空变量,因此无需额外使用可选链接。 Additionally, when you cast key into keyof typeof variable , you're asserting that it already exists so you can remove the optional chaining before ?.value as well.此外,当您将key转换为keyof typeof variable时,您是在断言它已经存在,因此您也可以删除?.value之前的可选链接。

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

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