[英]How to use optional chaining operator with variable in typescript
我有以下代碼,我想從變量 object 的值鍵中傳遞數字,如何將變量用於可選鏈接運算符來解決錯誤元素隱式具有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; }; }'.
})
這實際上不是可選鏈接問題,而是Object.keys
工作方式的問題。 Typescript 假定 object 可能具有比編譯時已知的更多的鍵,因此這里的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
之前的可選鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.