相关疑难解决方法(0)

在TypeScript中,如何将布尔值转换为数字,如0或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];
Run Code Online (Sandbox Code Playgroud)

在编译时,它会出错

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

然后我尝试使用any类型:

let action: string = actions[<number> <any> isPlay];
Run Code Online (Sandbox Code Playgroud)

也出问题了.我该如何重写这些代码.

javascript typecast-operator typescript

10
推荐指数
2
解决办法
9459
查看次数

标签 统计

javascript ×1

typecast-operator ×1

typescript ×1