a2h*_*uen 10 javascript typecast-operator typescript
我们知道,类型转换在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)
也出问题了.我该如何重写这些代码.
Nit*_*mer 28
你不能只是转换它,问题是在运行时不仅在编译时.
你有几种方法可以做到这一点:
let action: string = actions[isPlay ? 1 : 0];
let action: string = actions[+isPlay];
let action: string = actions[Number(isPlay)];
Run Code Online (Sandbox Code Playgroud)
这些应该适用于编译器和运行时.
您可以使用以下命令将任何内容转换为布尔值,然后转换为数字+!!
:
const action: string = actions[+!!isPlay]
Run Code Online (Sandbox Code Playgroud)
例如,当您希望至少满足三个条件中的两个,或者正好满足一个条件时,这会很有用:
const ok = (+!!something) + (+!!somethingelse) + (+!!thirdthing) > 1
const ok = (+!!something) + (+!!somethingelse) + (+!!thirdthing) === 1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9459 次 |
最近记录: |