Let's dissect the code snippet provided below:
class Person {
private name: string;
constructor(name){
this.name = name;
}
}
let p = new Person(5)
The above code does not result in any errors. One would expect an error to occur during the constructor call, where the value 5
is passed.
It appears that the name
parameter in the constructor is being inferred as any
, even though it is clear that we are assigning it to private name: string
.
So the question remains: is there a specific reason why TypeScript allows the value 5
here - or put differently - why is name
being inferred as any
, when it should clearly be a string in this context?
I am aware that I could define another class structure like this:
class Person {
constructor(
private name: string
){}
}
In this case, the parameter type is explicitly specified, eliminating any inference. Similarly, I could also write:
class Person {
private name: string;
constructor(name: string){
this.name = name;
}
}
and avoid any inference as well. However, my focus here is on understanding the mechanism of inference and why it operates in this manner.