【发布时间】: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; }; }'.
})
【问题讨论】:
-
.[key]看起来语法无效。鉴于您通过循环访问变量来获取密钥,因此该变量必须存在。variable[key]在 forEach 中应该始终有效 -
@Taplar 不是
.[key]而是?.[key],它是一个新的复合运算符。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
?没有安全操作员吗? -
@Taplar 这是一个
?.[]运算符,可选链接+索引。
标签: javascript typescript typescript2.0 typescript1.5 typescript1.9