As a new TypeScript user, I'm looking for ways to prevent incorrect types from creeping into my data structures. I was surprised that TypeScript did not restrict the assignment of this.myString = myArgument
, even though the type of myArgument
is unknown.
class MyClass {
private myString : string;
constructor(myArgument) {
this.myString = myArgument;
}
}
let myInstance = new MyClass(3);
console.log("my instance", myInstance);
During runtime, the value of myInstance.myString
will be a number instead of a string which is definitely not what I intended. While I could explicitly specify myArgument : string
as the parameter argument type, I expected TypeScript's type inference feature to handle this scenario automatically.
So, how can I safeguard against incorrect types infiltrating my data structures?