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?

4
  • What is myType value? empty string? Commented Sep 12, 2018 at 13:20
  • Isn't let a = myType as boolean; enough? Commented Sep 12, 2018 at 13:20
  • 10
    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). Commented Sep 12, 2018 at 13:21
  • Seconding what @briosheje said, this can give you more info on type assertion versus type casting. Commented Sep 12, 2018 at 13:22

1 Answer 1

34

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.