Reputation: 1443
I can do it in typescript like this:
let greet: 'Hey' | 'Hi' | 'Hello';
// Now greet will allow only above specified string values
greet = 'Hi'; // no Type Error here
greet = 'Welcome'; // throws a Type Error
How do I implement the equivalent in Dart?
Upvotes: 4
Views: 801
Reputation: 17141
You can use an enumerated type and convert it to a String
if necessary.
Declaring the enum:
enum Greet {
Hey,
Hi,
Hello,
}
Providing a method of converting to string with an extension method:
extension ParseToString on Greet {
String toShortString() {
return this.toString().split('.').last;
}
}
Example usage:
void main() {
Greet greet = Greet.Hey;
print(greet.toShortString());//Hey
}
enum Greet {
Hey,
Hi,
Hello,
}
extension ParseToString on Greet {
String toShortString() {
return this.toString().split('.').last;
}
}
If you just needed a type that had a few distinct values, you can ignore the String extension part.
Upvotes: 4