In TypeScript, How to cast boolean to number, like 0 or 1

a2htray yuen picture a2htray yuen · Apr 28, 2017 · Viewed 22.1k times · Source

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.

Answer

Nitzan Tomer picture Nitzan Tomer · Apr 28, 2017

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.