我们知道,类型转换在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)
也出问题了.我该如何重写这些代码.