4

Given the following simple 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'
        }
    }

Furthermore, in tsconfig.json, the flags strictNullChecks and strict are enabled.

Although subscribers is checked for a key of the current event, the typescript compiler complains with the error message shown above (this.subscribers.get(event) is possibly undefined).

If I'm not completely wrong, this.subscribers.get(event) can never be undefined in this case.

How can I get rid of that message?

belwood
  • 2,444
  • 10
  • 32
  • 38
tklepzig
  • 558
  • 7
  • 19

1 Answers1

17

Typing of Map explicitly states that get can result in undefined:

interface Map<K, V> {
    ...
    get(key: K): V | undefined;
    ...
}

That's why you're getting error with strictNullChecks enabled.

You can use non-null assertion operator to inform the compiler that you're sure that it actually has value:

this.subscribers.get(event)!.push(callback);

Another option (the better one in my opinion) is to refactor your code in following way:

public subscribe(event: string, callback: (data: any) => void) {
    let callbacks = this.subscribers.get(event);
    if (!callbacks) {
        callbacks = []
        this.subscribers.set(event, callbacks);
    }

    callbacks.push(callback);
}
Aleksey L.
  • 25,602
  • 7
  • 55
  • 64