corgrath corgrath - 1 month ago 7
TypeScript Question

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

You can use the following code at the playground to verify it.

Given this code:

class Alpha {

private beta;

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

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

}

class Beta {

}


I kinda expected the compiler error
Property 'doesNotExist' does not exist on type 'Beta'.
.

But you only get that if you put the type on
beta
such as:

private beta:Beta;


I thought TypeScript had type inference for parameter assignments. For example, the parameter
b
is of type
Beta
. That you can verify if you add this to the constructor:

const test:string = beta;


and then you get the compiler error
Type 'Beta' is not assignable to type 'string'.
.

So my question is, why doesn't
private beta
be of type
beta
?

Or is this just something I need to learn and always put types on all private constructor members?

Answer

I thought TypeScript had type inference for parameter assignments

Nope.

Fix

There are actually two:

Annotate the member explicitly

class Alpha {

        private beta: Beta; // annotate

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

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

}

class Beta {

}

Combine the parameter and the member declaration (better)

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

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

}

class Beta {

}

More

Some notes on inference : https://basarat.gitbooks.io/typescript/content/docs/types/type-inference.html

Comments