简体   繁体   English

打字稿:Map <>与strictNullChecks的使用

[英]Typescript: Usage of Map<> with strictNullChecks

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. 此外,在tsconfig.json中,启用了strictNullChecksstrict标志。

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). 尽管已检查subscribers当前事件的键,但打字稿编译器this.subscribers.get(event)显示上述错误消息( this.subscribers.get(event)可能未定义)。

If I'm not completely wrong, this.subscribers.get(event) can never be undefined in this case. 如果我没有完全错,在这种情况下,永远this.subscribers.get(event) undefined this.subscribers.get(event)

How can I get rid of that message? 我如何摆脱该信息?

Typing of Map explicitly states that get can result in undefined : 明确键入Map状态表明get可能导致undefined

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

That's why you're getting error with strictNullChecks enabled. 这就是为什么在启用strictNullChecks时出错。

You can use non-null assertion operator to inform the compiler that you're sure that it actually has value: 您可以使用非null断言运算符来通知编译器您确定它确实具有值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM