在TypeScript中,如何将布尔值转换为数字,如0或1 [英] In TypeScript, How to cast boolean to number, like 0 or 1
本文介绍了在TypeScript中,如何将布尔值转换为数字,如0或1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们知道,类型转换在TypeScript中称为断言类型。以下代码部分:
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];
编译时出错
Error:(56, 35) TS2352: Neither type 'boolean' nor type 'number' is assignable to the other.
然后我尝试使用任何
类型:
let action: string = actions[<number> <any> isPlay];
也出错了。我怎样才能重写这些代码。
Also go wrong. How can I rewrite those code.
推荐答案
你不能只是强制转换它,问题是在运行时不仅在编译时。
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.
这篇关于在TypeScript中,如何将布尔值转换为数字,如0或1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文