15

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.

Benjamin J.
  • 1,239
  • 1
  • 15
  • 28
babbaggeii
  • 7,577
  • 20
  • 64
  • 118

1 Answers1

25

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));
babbaggeii
  • 7,577
  • 20
  • 64
  • 118
Nathan Friend
  • 12,155
  • 10
  • 75
  • 125
  • 2
    This remains a problem though if the non-null assertion operator is forbidden by the lint rules in the project. – Yamo93 Sep 15 '22 at 08:49