如何在打字稿中使用带有变量的可选链接运算符
How to use optional chaining operator with variable in typescript
我有以下代码,我想从变量对象的值键传递数字,我如何使用变量作为可选链接运算符来解决错误 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; }; }'.
})
这实际上不是可选链接问题,而是 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
之前的可选链接。
我有以下代码,我想从变量对象的值键传递数字,我如何使用变量作为可选链接运算符来解决错误 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; }; }'.
})
这实际上不是可选链接问题,而是 Object.keys
工作方式的问题。 Typescript assumes that an object may have more keys than is known at compile time 所以这里 key
的类型是 string
而不是 keyof variable
。要解决这个问题,您必须使用
Object.keys(variable).forEach((key) => {
fun(variable[key as keyof typeof variable].value)
})
当您在 Object.keys
中使用它时,您已经将 variable
视为非空变量,因此无需额外使用可选链接。此外,当您将 key
转换为 keyof typeof variable
时,您断言它已经存在,因此您也可以删除 ?.value
之前的可选链接。