打字稿:Map<>的用法with strictNullChecks

时间:2017-11-19 11:12:15

标签: javascript typescript dictionary strictnullchecks

给出以下简单类:

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'
        }
    }

此外,在tsconfig.json中,标志strictNullChecksstrict已启用。

虽然检查了subscribers当前事件的密钥,但是typescript编译器会抱怨上面显示的错误消息(this.subscribers.get(event)可能未定义)。

如果我没有完全错误,this.subscribers.get(event)在这种情况下永远不会是undefined

我怎样才能摆脱那条消息?

1 个答案:

答案 0 :(得分:5)

Map的输入明确指出get可能导致undefined

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

这就是为什么你在启用strictNullChecks时遇到错误的原因。

您可以使用non-null assertion operator通知编译器您确定它确实具有值:

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

另一个选项(我认为越好)是以下列方式重构您的代码:

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);
}