【问题标题】:How to use optional chaining operator with variable in typescript如何在打字稿中使用带有变量的可选链接运算符
【发布时间】:2020-08-01 07:25:34
【问题描述】:

我有以下代码,我想从变量对象的值键中传递数字,如何将变量用于可选链接运算符来解决错误元素隐式具有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; }; }'.
    })

【问题讨论】:

标签: javascript typescript typescript2.0 typescript1.5 typescript1.9


【解决方案1】:

这实际上不是可选链接问题,而是Object.keys 工作方式的问题。 Typescript assumes that an object may have more keys than is known at compile time 所以key 的类型是string 而不是keyof variable。为了解决这个问题,您必须让 TS 编译器知道所有键在编译时都是已知的,使用

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

当您在Object.keys 中使用variable 时,您已经将其视为非空变量,因此无需额外使用可选链。此外,当您将key 转换为keyof typeof variable 时,您是在断言它已经存在,因此您也可以删除?.value 之前的可选链接。

【讨论】:

  • 好的,那么你将如何做类似variable && Object.keys(variable).length>1 的事情?如果它是对象上的一个方法,它会是 variable?.keys().length > 1 但它不是...
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多