Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  167] [ 2]  / answers: 1 / hits: 22746  / 6 Years ago, wed, september 12, 2018, 12:00:00

I was trying to cast a type any to boolean. So I simply did this:



let a = (<any>myType) as boolean;


But a was not a boolean it just contains myType value.
However When I try this:



let b = Boolean(myType);


b returns a boolean which is false.



Am I missing something about as casting?



Which one is correct to cast to boolean?


More From » typescript

 Answers
249

Casting — or more properly, type assertion — is not conversion/coercion. It has no runtime effect in TypeScript.¹ It's just the process of telling TypeScript that a variable or property is of the type you're casting it to asserting. In your first example, a gets the exact same value that myType has in it, it's just that the TypeScript compiler then believes a contains a boolean. That type information disappears before the code is run, since TypeScript is compiled to JavaScript without decorating the code to convey type information, and JavaScript variables are loosely typed.


To actually convert the value, you'd use conversion (such as your Boolean(myType) example) instead.




¹ Don't over-generalize this to other languages, such as Java or C#. This is one of the reasons TypeScript calls the process type assertion rather than casting. Casting may or may not be conversion in those other languages depending on the cast; and separately casting in those other languages can have an effect on runtime behavior.


[#53508] Sunday, September 9, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleew

Total Points: 70
Total Questions: 87
Total Answers: 117

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
harleew questions
;