8

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?

Mhd
  • 2,778
  • 5
  • 22
  • 59
  • What is myType value? empty string? – asdf_enel_hak Sep 12 '18 at 13:20
  • Isn't `let a = myType as boolean;` enough? – lagerone Sep 12 '18 at 13:20
  • 7
    `as` is just a keyword (**in typescript**) to actually say something like "Hey, typescript compiler, **I AM TELLING YOU** that this value is a boolean, **trust me**"... And it does trust you, you are telling it to trust you, and it does. However, at runtime, it just doesn't matter if it trusts you or not. If that variable is **not** a boolean, it won't be such, you need to cast it **manually** (either use "bang bang, you're a boolean", or just use `Boolean` as you did). – briosheje Sep 12 '18 at 13:21
  • Seconding what @briosheje said, [this](https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html) can give you more info on type assertion versus type casting. – meyi Sep 12 '18 at 13:22

1 Answers1

28

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875