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

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

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

// the variable will change to true at onetime
let isPlay: boolean = false;
let actions: string[] = ['stop', 'play'];
let action: string = actions[<number> isPlay];

编译时出错

Error:(56, 35) TS2352: Neither type 'boolean' nor type 'number' is assignable to the other.

然后我尝试使用 any 类型:

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

同样出错。我该如何重写这些代码。

不能直接强制转换,问题出在运行时,不仅仅是编译时。

您有几种方法可以做到这一点:

let action: string = actions[isPlay ? 1 : 0];
let action: string = actions[+isPlay];
let action: string = actions[Number(isPlay)];

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

您可以使用 +!!:

将任何内容转换为布尔值,然后再转换为数字
const action: string = actions[+!!isPlay]

例如,当您希望至少满足三个条件中的两个条件,或者只满足一个条件时,这会很有用:

const ok = (+!!something)  + (+!!somethingelse) + (+!!thirdthing) > 1
const ok = (+!!something)  + (+!!somethingelse) + (+!!thirdthing) === 1