在 TypeScript 中,如何将布尔值转换为数字,例如 0 或 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43687958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:29:50  来源:igfitidea点击:

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

javascripttypescripttypecast-operator

提问by a2htray yuen

As we know, the type cast is called assertion type in TypeScript. And the following code section:

众所周知,类型转换在 TypeScript 中称为断言类型。以及以下代码部分:

// 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 anytype:

然后我尝试使用any类型:

let action: string = actions[<number> <any> isPlay];

Also go wrong. How can I rewrite those code.

也会出错。我怎样才能重写这些代码。

回答by Nitzan Tomer

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.

这些对于编译器和运行时都应该没问题。

回答by user239558

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