首页 > 解决方案 > 强制使用空值

问题描述

我想要一个可以是数字或空值的变量。这样做的目的是多次重置变量(通过将其设置为空)。问题是如果我用 type 声明变量number | null,我不能像我知道它是一个数字的数字一样使用它。

这是代码:

class Test {
    start: number | null = null;

    handler(e: Event) {
        if (this.start === null) {
            this.start = Date.now();
        }

        let time = Date.now() - this.start;
        if (time < 1000) {
            this.start = null;
        }
        // ...
    }
}

编译器说this.start“可能为空”。我怎么能说它是对的?否则,是我的模式有问题吗?我应该改用布尔属性hasStarted,所以start总是一个数字(或未定义的顺便说一句)?

标签: typescript

解决方案


更改start: number | nullstart?: number让编译器知道您知道它有时可能为空并且您将处理它。


推荐阅读