TypeScript 对构造函数参数的类型推断——我认为这行得通吗?

TypeScript's type inference for constructor parameters - I thought this would work?

您可以在playground处使用以下代码进行验证。

鉴于此代码:

class Alpha {

        private beta;

        constructor(b: Beta) {
                this.beta = b;
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

我有点预料到编译器错误 Property 'doesNotExist' does not exist on type 'Beta'.

但是只有将类型放在 beta 上才能得到,例如:

private beta:Beta;

我认为 TypeScript 具有参数分配的类型推断。例如,参数 b 的类型为 Beta。您可以验证是否将其添加到构造函数中:

const test:string = beta;

然后你得到编译器错误 Type 'Beta' is not assignable to type 'string'.

所以我的问题是,为什么 private beta 不是 beta 类型?

或者这只是我需要学习并始终将类型放在所有私有构造函数成员上的东西吗?

I thought TypeScript had type inference for parameter assignments

没有。

修复

实际上有两个:

显式注释成员

class Alpha {

        private beta: Beta; // annotate

        constructor(b: Beta) {
                this.beta = b;
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

合并参数和成员声明(更好)

class Alpha {
        constructor(private beta: Beta) { // notice `private`
        }

        doSomething() {
                this.beta.doesNotExist();
        }

}

class Beta {

}

更多

关于推理的一些注释:https://basarat.gitbooks.io/typescript/content/docs/types/type-inference.html