tslints” typedef”和typescript编译器” noImplicitAny”有什么区别?

What is the difference between tslints “typedef” and typescript compilers “noImplicitAny”?

我正在使用tslint整理typescript代码。我已经搜索了一段时间,但找不到使用typescript编译器选项noImplicitAny和tslint中的以下配置之间存在什么区别(如果有):

1
2
3
4
5
6
7
"no-inferrable-types": [true]
"typedef": [
  true,
 "property-declaration",
 "variable-declaration",
  // ... etc ...
]

存在差异并且差异很大。

NoImplicite any会在将变量识别为any并且未直接键入变量时抛出错误,例如::

1
2
3
4
5
let arr = []
arr.forEach(item => item) // Variable 'arr' implicitly has an 'any[]' type.(7005)

// but
[1,2,3].map(item => item) // OK

在第二种情况下,未声明项类型(如第一种情况),但是TS编译器知道什么是item变量(必须使用number

调用Array<number>上的映射

也这样的代码:

1
2
let arr = []
arr.forEach((item: any) => item) // OK

不会引发错误。 item被键入为any,但它是显式的,而不是隐式的。

在linter规则的情况下,它们只是强制您添加类型定义,因此此代码[1,2,3].map(item => item)将通过编译,但是linter会产生错误。