我有以下代码,想要从变量对象的值键中传递数字,我该如何使用可选链运算符的变量来解决 "Element implicitly has an any type" 的错误?
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]
看起来像是无效的语法。考虑到您正在通过循环变量获取键,那么该变量必须存在。在 forEach 中,variable[key]
应该始终有效。 - Taplar.[key]
,而是?.[key]
,这是一个新的复合运算符。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining - zerkms?.[]
操作符,可选链接加索引。 - zerkms