I\'m trying to understand why TypeScript is giving me the following error: Object is possibly \'undefined\'
Here\'s the code snippet:
There is no type guarding for Map.has()
See this issue or this issue.
You can fix the issue by having a fallback of 0
, -1
or whatever you think would be best for your code.
const mergedDepsObj: { [key: string]: string } = {}
const results: Map = new Map();
Object.keys(mergedDepsObj).forEach((key: string) => {
results.has(key) ? results.set(key, (results.get(key) || 0) + 1) : results.set(key, 0);
})
However, above being said, we make our own type guard with help from this comment.
interface Map {
// Works if there are other known strings.
has(this: MapWith, key: CheckedString): this is MapWith
has(this: Map, key: CheckedString): this is MapWith
}
interface MapWith extends Map {
get(k: DefiniteKey): V;
}
const mergedDepsObj: { [key: string]: string } = {}
const results: Map = new Map();
Object.keys(mergedDepsObj).forEach((key: string) => {
results.has(key) ? results.set(key, results.get(key) + 1) : results.set(key, 0);
})
We can see it in action here