I have following code and I would like to pass number from value key of variable object, How can I use variable for optional chaining operator for it to solve the error 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]looks like invalid syntax. Given that you are getting the key by looping over the variable, the variable has to exist.variable[key]should always be valid in the forEach.[key]it's?.[key], it's a new composite operator. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…?there isn't the safety operator??.[]operator, optional chaining + indexing.