typescript - 为什么 TypeScript 在分配给新的空数组时不暗示数组类型?
问题描述
我通常有以下代码:
class Foo {
foo: SomeType[];
doSomething() {
const a = this.foo = [];
}
}
在这种情况下,a
将是any[]
or never[]
(取决于环境)而不是SomeType[]
. 如果我指定noImplicitAny
那些暗示any[]
,编译器会抛出一个错误。
我知道下面的演员表解决了这个问题,但为什么 TypeScript 不能从中推断出类型this.foo
?
const a: SomeType[] = this.foo = []; // Have to repeat the type again
可重现的代码:
tsconfig.json
:
{
"compilerOptions": {
"noImplicitAny": true
}
}
test.ts
:
class Foo {
foo: number[];
doSomething() {
const a = this.foo = [];
}
}
解决方案
被推断为的类型是any[]
有意义的,因为 Javascript 与assignment
运算符是右关联的。
看到这个问题:Multiple left-hand assignment with JavaScript
这意味着表达式:
const a = this.foo = [];
被解释为:
this.foo = [];
const a = [];
如您所见,类型信息与空数组无关,因此any[]
是最正确的类型。
您可以通过一个简单的示例证明这实际上是正在发生的事情:
let t: number;
const a = t = 5;
的推断类型a
将是文字 number 5
,而不是number
(这是 的类型t
)。
在这种情况下,打字稿游乐场似乎是错误的,这就是为什么许多人(包括我自己)报告never[]
为推断类型的原因。
推荐阅读
- python - 如何从 github python 安装“sparse_dot_topn”
- ios - 从中国商店最好的方法中禁用Callkit?
- javascript - JavaScript - 等待异步函数完成
- javascript - chrome扩展拒绝执行内联脚本
- python - 准确度/损失图中的数字缺失点
- jquery - jQuery Lightbox 2 在随机图像中显示边框
- node.js - 子模块是否存在相反或相反的情况?
- php - 如何在对 XPLAN API 的 CURL 请求中构造 edai.Search 方法的第三个参数?
- dns - 为 DNS 区域文件提取域
- google-app-engine - appIdentityService.signForApp (Java) 和 app_identity.sign_blob (Python) 结果不同