skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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();
    }
    
    class MyInt extends MyUnion {
      const MyInt(this.val);
      final int val;
    }
    
    class MyString extends MyUnion {
      const MyString(this.val);
      final String val;
    }
    
    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search