Let's analyse code snippet below:
class Human {
private name: string;
constructor(name){
this.name = name;
}
}
let h = new Human(5)
Above code doesn't throw any error. And I'd expect it to throw in the constructor call, where I pass 5.
It seems that constructor's name parameter gets inferred as any, where, statically it's easy to find out that I'm assigning it to a private name: string.
The question is: is there any particular reason that TypeScript is allowing 5 here - or in other words - that name is inferred as any, when in this case it's obvious that it has to be a string?
I know I could do another class definition like this:
class Human {
constructor(
private name: string
){}
}
but here I specify the parameter type, so there's no inference here. The same way I could do:
class Human {
private name: string;
constructor(name: string){
this.name = name;
}
}
and there would be no inference either. My question is about inference - why it works this way.
anymade this way. - Val