【问题标题】:In TypeScript, How to cast boolean to number, like 0 or 1在 TypeScript 中,如何将布尔值转换为数字,例如 0 或 1
【发布时间】:2017-09-27 00:43:14
【问题描述】:

众所周知,类型转换在 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];

也会出错。我该如何重写这些代码。

【问题讨论】:

  • actions[isPlay ? 1 : 0]

标签: javascript typescript typecast-operator


【解决方案1】:

你不能只转换它,问题出在运行时,而不仅仅是在编译时。

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

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

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

【讨论】:

  • 第二种方式并不是真正的自我记录,除非你知道你可以这样做。否则,第一种方法对于查看您的代码的任何其他开发人员来说一目了然。
【解决方案2】:

您可以使用 +!! 将任何内容转换为布尔值,然后再转换为数字:

const action: string = actions[+!!isPlay]

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

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

【讨论】:

  • 为什么+!!而不仅仅是 +?
  • @MarkLopez !!强制表达式为真或假,所以 +!!变为 0 或 1。例如,如果 something 为 4,则 +!!4 为 1,而 +4 为 4。所以 +!!帮助您计算布尔真表达式的数量。
  • +undefined 是 NaN 但 +!!undefined 是零。
猜你喜欢
  • 2022-07-28
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2013-10-07
  • 2013-01-24
相关资源
最近更新 更多