[英]Typescript not enforcing or checking return type
A bug in our code ended up being caused by the below. 我们的代码中的错误最终是由以下原因引起的。 The output of the method was being compared against 0 and returning false.
该方法的输出与0进行比较并返回false。 The method is explicitly declaring a number return type, but allowing a string to be returned.
该方法显式声明一个数字返回类型,但允许返回字符串。 I would have epxected this to be flagged as an error at some point between compiler and lint, but is never caught.
我本来希望在编译器和lint之间的某个时刻将其标记为错误,但始终不会被捕获。
Comparison: 比较:
if(routerIdParameter() === 0) {
console.log('They match');
} else {
console.log('They do not match');
}
Method: 方法:
public routerIdParameter(): number {
if (this.route.snapshot.paramMap.has('id')) {
return this.route.snapshot.params['id'];
} else {
return 0;
}
}
Obviously the problem line is return this.route.snapshot.params['id'] . 显然问题所在是返回this.route.snapshot.params ['id'] 。 params type is [key: string]: any so it can't know the type, and there is where I assumed type checking would complain.
params type是[key:string]:任何它都不知道类型,因此我认为类型检查会在哪里抱怨。 There is the easy fix of prefixing it with + but I'm more concerned with my gap in understanding as to why it is allowed.
用+前缀可以很容易地解决,但是我更担心我为什么允许它的空白。
Any explanation to why this is happening or how to make it error would be appreciated as I'm concerned there could be more of this throughout our app. 关于这种情况为什么发生或如何使其出错的任何解释将不胜感激,因为我担心整个应用程序中可能会有更多这种情况。
Identified in typescript 2.3.4 but also reproduced in 3.1.6 在打字稿2.3.4中标识,但也在3.1.6中转载
this.route is of type ActivatedRoute imported from @angular/router this.route是从@ angular / router导入的ActivatedRoute类型
any
by definition is assignable from any type and assignable to any type. any
定义为任何类型的分配和分配给任何类型的。 There is no compiler setting to make this stricter. 没有编译器设置可以使其更严格。
Where possible you should prefer unknown
(introduced in typescript 3.0) which is assignable from any type but not assignable to any type (read here for more info on any
vs unknown
). 在可能的情况下,您应该首选
unknown
(在typescript 3.0中引入),它可以从任何类型分配,但不能分配给任何类型(有关any
vs unknown
信息,请参见此处 )。
As to how you can avoid this behavior, I would suggest looking into the tslint rule no-unsafe-any
至于如何避免这种行为,我建议您研究tslint规则
no-unsafe-any
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.