You can experiment with the given code snippet at the online playground to confirm it.
Consider this code:
class Alpha {
private beta;
constructor(b: Beta) {
this.beta = b;
}
doSomething() {
this.beta.doesNotExist();
}
}
class Beta {
}
I was expecting the compiler error
Property 'doesNotExist' does not exist on type 'Beta'.
.
However, you only receive that error if you specify the type for beta
like this:
private beta:Beta;
I assumed TypeScript would infer types for parameter assignments. For instance, the parameter b
is of type Beta
. You can verify this by adding the following in the constructor:
const test:string = beta;
Upon doing so, you will encounter an error message stating
Type 'Beta' is not assignable to type 'string'.
.
Hence, my query is, why isn't private beta
automatically assigned the type of beta
?
Or is this a lesson I need to learn and consistently specify types for all private constructor members?