【发布时间】:2019-01-24 23:53:21
【问题描述】:
我们代码中的一个错误最终是由以下原因引起的。该方法的输出与 0 进行比较并返回 false。该方法显式声明了一个数字返回类型,但允许返回一个字符串。我本以为这会在编译器和 lint 之间的某个时刻被标记为错误,但从未被捕获。
比较:
if(routerIdParameter() === 0) {
console.log('They match');
} else {
console.log('They do not match');
}
方法:
public routerIdParameter(): number {
if (this.route.snapshot.paramMap.has('id')) {
return this.route.snapshot.params['id'];
} else {
return 0;
}
}
显然问题是 return this.route.snapshot.params['id']。 params type 是 [key: string]: any 所以它不知道类型,而且我认为类型检查会抱怨。 用 + 前缀很容易解决,但我更担心我在理解为什么允许它方面存在差距。
任何关于为什么会发生这种情况或如何使其出错的解释都将不胜感激,因为我担心在我们的应用程序中可能会有更多这样的情况。
在 typescript 2.3.4 中标识,但也在 3.1.6 中复制
this.route 是从 @angular/router 导入的 ActivatedRoute 类型
【问题讨论】:
标签: typescript