typescript - 强制使用空值
问题描述
我想要一个可以是数字或空值的变量。这样做的目的是多次重置变量(通过将其设置为空)。问题是如果我用 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
总是一个数字(或未定义的顺便说一句)?
解决方案
更改start: number | null
为start?: number
让编译器知道您知道它有时可能为空并且您将处理它。
推荐阅读
- jhipster - 纱线安装 - 私有注册表后面的哈希错误 - Jhipster v5 升级
- python - 当列表中的元组没有返回任何内容时写入错误
- python - 使用 Python Wand 使 GIF 只播放一次
- tpanel - 我必须设置什么以便标签文本将自动换行到父面板的宽度?
- spring-boot - Spring Cloud Config 双引导文件行为
- orleans - 引用与另一种谷物相关的谷物的正确方法
- jquery - JSON响应太晚了
- android - 没有从 recyclerView 内的按钮调用 onClick 回调
- python - 从创建 HTTPStatus 对象中获取 linting 错误
- h2o - 如何使用 CURL 从命令行获取 H2O automl?