Consider the following basic class:
class Observer {
private subscribers: Map<string, Array<((data: any) => void)>> = new Map();
public subscribe(event: string, callback: (data: any) => void) {
if (!this.subscribers.has(event)) {
this.subscribers.set(event, []);
}
this.subscribers.get(event).push(callback); //tsc says: Object is possibly 'undefined'
}
}
In addition, with strictNullChecks
and strict
enabled in tsconfig.json.
Even though we are checking for a key in subscribers
with the current event, the TypeScript compiler raises an error suggesting that this.subscribers.get(event)
could be undefined.
Is it possible for this.subscribers.get(event)
to actually be undefined
here?
How can we resolve or suppress this warning message?