As we know, the type cast is called assertion type in TypeScript. And the following code section:
// the variable will change to true at onetime
let isPlay: boolean = false;
let actions: string[] = ['stop', 'play'];
let action: string = actions[<number> isPlay];
On compiling, it go wrong
Error:(56, 35) TS2352: Neither type 'boolean' nor type 'number' is assignable to the other.
Then I try to use the any
type:
let action: string = actions[<number> <any> isPlay];
Also go wrong. How can I rewrite those code.
Using the method booleanObjectMethodToInt, we can convert a boolean value to an integer the same way we did with the static method. Similarly, you can apply the reversed version by changing the argument to true and adding 1 to the result.
You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .
A Boolean number has value True/ON and False/OFF; therefore, when a Boolean is converted into a number it would return 1 or 0 for True/ON or False/OFF respectively.
Today, we will know the easiest way to convert boolean to number in typescript. TypeScript has + unary operator which helps you to convert boolean to the number when we add a unary operator with true it will return 1, and with false it will return 0.
The Boolean is an object wrapper for the primitive boolean value. Also, let us find the difference between Boolean object vs boolean primitive. The Typescript also has a Boolean global function, which we use to convert any value to boolean primitive type.
TypeScript Data Type - Boolean. Boolean values are supported by both JavaScript and TypeScript and stored as true/false values. TypeScript Boolean: let isPresent:boolean = true; Note that, Boolean with an upper case B is different from boolean with a lower case b. Upper case Boolean is an object type whereas lower case boolean is a primitive type.
While you can't cast a number directly to a boolean, you can cast it to the wrapper Boolean class and immediately unwrap it. For example: foo(<boolean><Boolean>xxx); While clumsy, it avoids the type erasure of casting to <any>. It's also arguably less obscure & more readable than the !!approach (certainly so in the transpiled js code). Share
You can't just cast it, the problem is at runtime not only at compile time.
You have a few ways of doing that:
let action: string = actions[isPlay ? 1 : 0];
let action: string = actions[+isPlay];
let action: string = actions[Number(isPlay)];
Those should be fine with both the compiler and in runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With