是否可以在Dart中使用TypeScript中的类型?
样本(TypeScript):
export type Speed = 'very slow' | 'slow' | 'normal' | 'fast' | 'very fast';
public getRealSpeed(speed: Speed): number {
switch(speed) {
...
}
return 0;
}
或
public getRealSpeed(speed: 'slow' | 'fast' | 'unknown'): number {
switch(speed) {
//TODO
}
return 0;
}
答案 0 :(得分:1)
您可以将Dart枚举用于相同的行为:
enum Speed { verySlow, slow, normal, fast, veryFast; }
int getRealSpeed(Speed speed) {
switch (speed) {
case Speed.verySlow: return 1;
...
case Speed.veryFast: return 99;
}
return 0;
}
这确实意味着您必须使用
将字符串值显式转换为Speed
实例。
const speedByName = {
"very slow": Speed.verySlow,
"slow": Speed.slow,
"normal": Speed.normal,
"fast": Speed.fast,
"very fast": Speed.veryFast,
};