Search code examples
typescripttype-safety

How to prevent assignment of wrong type in TypeScript?


I'm new to TypeScript and want to get rid of wrong types sneaking into my data structures. I thought TypeScript would forbid the following assignment of this.myString = myArgument since 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);

At runtime myInstance.myString will be a number which is highly undesirable :( I know I probably could add myArgument : string as parameter argument type declaration but I thought one of the strengths of TypeScript is type inference which should be easy here?

How can I prevent wrong types ending up in my data structures?


Solution

  • If you want to ensure that all values must have specified types you can set noImplicitAny to true in tsconfig.json.