首页 > 解决方案 > 为什么 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 = [];
    }

}

TypeScript 投诉(至少在 VS Code 中): 在此处输入图像描述

标签: typescripttypescastingvariable-assignmentimplicit-typing

解决方案


被推断为的类型是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[]为推断类型的原因。


推荐阅读