0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.