Otpidus
Otpidus

Reputation: 519

TypeScript - Why allow assign string to a number

My question is why allow the following if TypeScript is for type safely? Is there a flag for tsconfig to stop this?

let strNum: any = "2";
let numTest: number;
numTest = strNum;
console.log(`Type of number is: ${typeof numTest}`) 
// Output number is: string

Upvotes: 0

Views: 130

Answers (1)

user12251171
user12251171

Reputation:

Because you're setting your string to the any type:

let strNum: any = "2";

If you did just:

let strNum = "2";

TypeScript will complain and say "type string is not assignable to type number".


Also, when you log typeof numTest, that is JavaScript running, not TypeScript. TypeScript only knows anything about your code at compile time. Once you have running code TypeScript is out of the picture.

Upvotes: 2

Related Questions