How can I define a variable with only two possible primitive types, such as (String or num) for example, in Dart? Is there a way to do this? like union types in TypeScript.
const x:string|number;
How can I define a variable with only two possible primitive types, such as (String or num) for example, in Dart? Is there a way to do this? like union types in TypeScript.
const x:string|number;
On
I'll add another recommendation for Freezed. It's a good package that will solve your problem and can also be used for things like data classes w/ JSON support.
If you don't want to add dependencies / use code generation / whatever, you can write your own sealed class:
sealed class MyUnion {
const MyUnion();
static MyUnion fromResponse(Object response) {
return switch (response) {
int val => MyInt(val),
String val => MyString(val),
_ => throw UnimplementedError('Unsupported type ${response.runtimeType}'),
};
}
}
class MyInt extends MyUnion {
const MyInt(this.val);
final int val;
}
class MyString extends MyUnion {
const MyString(this.val);
final String val;
}
void main() {
printUnion(const MyInt(1));
printUnion(const MyString('Hello World'));
printUnion(MyUnion.fromResponse(10));
printUnion(MyUnion.fromResponse('ten'));
}
void printUnion(MyUnion arg) {
switch (arg) {
case MyInt(:final val):
print('Found int: $val');
case MyString(:final val):
print('Found String: $val');
}
}
As an aside: Dart does not have primitive types. It has built in types, but every type except Null is a subtype of Object.
Related Info/Resources:
This question is a possible duplicate of this question here.
There WAS a union package that has been discontinued. It was replaced by the freezed package, which includes the functionality you are looking for but with a bunch of other stuff as well.
I think you may be interested in dart's sealed classes or the either package.
Ideas for implementing from scratch:
To achieve the functionality you are looking for, you could create your own class that takes a dynamic type in its constructor, and throws an error if the type does not evaluate to one of the types that you want to enforce.