educative.io

[Please ignore] Why the variable "let castFromBoolean:number" can contain the value true?

const bool: boolean = true;
let castFromBoolean:number = (bool as unknown) as number;
console.log(castFromBoolean); // output true
console.log(typeof castFromBoolean); // output boolean

Please ignore my question, I found the reason “The fallacy of the cast when the underlying object doesn’t respect the type schema is one reason why it’s better to assign a type to the variable and not cast.


Type your question above this line.

Course: https://www.educative.io/collection/5892809498296320/4716987643068416
Lesson: https://www.educative.io/collection/page/5892809498296320/4716987643068416/6385020769927168

Dear @Thien_Nguyen,
Glad to hear you found the reason. In addition to this, “Casting is a delicate subject since you can cast any variable into anything else without properly respecting its original type. A particular case is “type assertion”. Type assertion is when you tell TypeScript what type an object is.”. You can refer to this explanation as well to make it more clear.

Hope it helps!