为什么 TypeScript 在分配给新的空数组时不暗示数组类型?

Why doesn't TypeScript imply array type when assigning to a new empty array?

我通常有以下代码:

class Foo {
    foo: SomeType[];

    doSomething() {
        const a = this.foo = [];
    }
}

在这种情况下,a 将是 any[]never[](取决于环境)而不是 SomeType[]。如果我在那些暗示 any[] 的对象上指定 noImplicitAny,编译器将抛出错误。

我知道下面的转换解决了这个问题,但为什么 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 = [];
    }

}

TypeScript 投诉(至少在 VS Code 中):

被推断为 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 的推断类型将是文字数字 5,而不是 numbert 的类型)。


在这种情况下,typescript playground 似乎是错误的,这就是为什么许多人(包括我自己)报告 never[] 为推断类型的原因。