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;
2
Answers
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.
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:
As an aside: Dart does not have primitive types. It has built in types, but every type except
Null
is a subtype ofObject
.