Reputation: 8629
Is it true that TypeScript is supposed to implicitly type variable based on what is assigned to it? I am getting this strange discrepancy - if I implicitly type variable by assignment and call non existing method TS does not throw an error if this happened inside of a class but throws an error if this happens outside of a class:
class Bar {
constructor() {
//do nothing;
}
}
class Foo {
bar1;
bar2: Bar;
constructor() {
//do nothing;
this.bar1 = new Bar();
this.bar1.asdasd();
this.bar2 = new Bar();
this.bar2.asdasd(); //error TS2094: The property 'asdasd' does not exist on value of type 'Bar'.
}
}
var bar3 = new Bar();
bar3.asdasd(); //error TS2094: The property 'asdasd' does not exist on value of type 'Bar'.
var bar4 : Bar = new Bar();
bar4.asdasd(); //error TS2094: The property 'asdasd' does not exist on value of type 'Bar'.
See how bar1 does not throw an error? Check out this playground example.
Upvotes: 2
Views: 629
Reputation: 220994
Variables in TypeScript infer their types from initializers, not from assignments. The bar1
field in your class is of type any
because it was not initialized and it does not have a type annotation. You can do anything with variables of type any
.
Upvotes: 1