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

拜拜、爱过 提交于 2019-12-10 02:02:01

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43687958/in-typescript-how-to-cast-boolean-to-number-like-0-or-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!