Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is possibly 'undefined' - after filter that contains check for undefined

Tags:

typescript

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.

like image 885
babbaggeii Avatar asked Feb 09 '18 12:02

babbaggeii


People also ask

How do you fix possibly undefined object?

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.

How do you handle undefined in typescript?

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.

How do you prevent 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.


1 Answers

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));
like image 103
Nathan Friend Avatar answered Oct 21 '22 18:10

Nathan Friend