Ale*_*eFe 9 types custom-type dart typescript
我想在 Dart 中创建自定义类型,就像在 Typescript 中一样。该类型应该是 String 的子类型,仅接受某些值。
例如,在 Typescript 中我会这样做:
type myType = 'HELLO' | 'WORLD' | '!'
Run Code Online (Sandbox Code Playgroud)
我如何在 Dart 中做同样的事情?
原始答案(请参阅下面的更新):这在 Dart 的语言级别上是不可能的 - 不过有一些替代方案。
您可以简单地定义一个枚举以及一个从枚举派生字符串的方法:
enum MyType {
hello,
world,
exclamationPoint,
}
String myTypeToString(MyType value) {
switch (value) {
case MyType.hello:
return 'HELLO';
case MyType.world:
return 'WORLD';
case MyType.exclamationPoint:
return '!';
}
}
Run Code Online (Sandbox Code Playgroud)
更新 2:在 Dart 3 中,我们还有另一种方法,使用密封类:
enum MyType {
hello,
world,
exclamationPoint,
}
String myTypeToString(MyType value) {
switch (value) {
case MyType.hello:
return 'HELLO';
case MyType.world:
return 'WORLD';
case MyType.exclamationPoint:
return '!';
}
}
Run Code Online (Sandbox Code Playgroud)
https://dart.dev/language/class-modifiers#sealed
旧更新:现在 Dart 2.17 支持在枚举上声明方法,因此可以比我原来的答案更干净地做到这一点:
enum MyType {
hello,
world,
exclamationPoint;
@override
String toString() {
switch (this) {
case MyType.hello:
return 'HELLO';
case MyType.world:
return 'WORLD';
case MyType.exclamationPoint:
return '!';
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以定义一个具有三个命名构造函数的类,并重写 toString 方法:
class MyType {
final String _value;
MyType.hello(): _value = 'HELLO';
MyType.world(): _value = 'WORLD';
MyType.exclamationPoint(): _value = '!';
@override
String toString() {
return _value;
}
}
// Usage:
void main() {
final hello = MyType.hello();
final world = MyType.world();
final punctuation = MyType.exclamationPoint();
// Prints "HELLO, WORLD!"
print("$hello, $world$punctuation");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5594 次 |
最近记录: |