In TypeScript, How to cast boolean to number, like 0 or 1
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.
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.
You can convert anything to boolean and then to a number by using +!!
:
const action: string = actions[+!!isPlay]
This can be useful when for example you want at least two out of three conditions to hold, or exactly one to hold:
const ok = (+!!something) + (+!!somethingelse) + (+!!thirdthing) > 1
const ok = (+!!something) + (+!!somethingelse) + (+!!thirdthing) === 1
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .