I'm doing an operation on an array like this:
.filter(key => actions && actions[key])
.forEach(key => actions[key](event, dispatch));
But I'm getting a TypeScript error on the forEach
actions
: Object is possibly 'undefined'
.
Yet it can't be 'undefined'
as it is filtered for those entries that do have actions
.
The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.
To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional statement or the optional chaining operator before accessing the object property in TypeScript.
I don't think the TypeScript compiler is smart enough to realize the filter
method has already removed all undefined
entries from the array. In this case, you can help the compiler out by telling it that actions[key]
is defined by using the non-null assertion operator !
as described in this answer:
https://stackoverflow.com/a/40350534/1063392
.filter(key => actions && actions[key])
.forEach(key => actions![key](event, dispatch));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With