TypeScript complaining even the code is correct?
So even I am initializing the object TypeScript keeps yelling
acc[key]
might be undefined. What am I missing?3 Replies
It is because it is unsafe. I assume you're using a
Map
, which is a good thing, you should take the advantage of has()
, get()
, set()
...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/MapMap - JavaScript | MDN
The Map object holds key-value pairs and remembers the original insertion
order of the keys. Any value (both objects and
primitive values) may be used as
either a key or a value.
I don't have the context of your use case, but maybe
groupBy
would be interesting: https://lodash.com/docs/4.17.15#groupBy
By the way, don't forget to specify typescript
when you write code in Discord so it gets syntax highlighted 😉Oh I see. I could not figure it out and did not occur to me using the
has()
, get()
... I will try to solve this way. Thank you!