jac*_*118 4 javascript typescript typescript1.5 typescript1.9 typescript2.0
我有以下代码,我想从变量对象的值键传递数字,如何使用变量作为可选链运算符来解决错误元素隐式具有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; }; }'.
})
Run Code Online (Sandbox Code Playgroud)
这实际上不是一个可选的链接问题,而是Object.keys工作原理的问题。Typescript 假设一个对象的键可能比编译时已知的要多,所以key这里的类型是string和不是keyof variable。为了解决这个问题,你必须让 TS 编译器知道所有的键在编译时都是已知的,使用
Object.keys(variable).forEach((key) => {
fun(variable[key as keyof typeof variable].value)
})
Run Code Online (Sandbox Code Playgroud)
variable当您使用它时,您已经将其视为非空变量,Object.keys因此无需在其上额外使用可选链接。此外,当您key转换为 时keyof typeof variable,您断言它已经存在,因此您也可以删除之前的可选链接?.value。
| 归档时间: |
|
| 查看次数: |
1402 次 |
| 最近记录: |