0

Can I constraint a typedef to range of integers in Dart?

Like shown in this TypeScript SO answer

type MyRange = 5|6|7|8|9|10

let myVar:MyRange = 4; // oops, error :)

I would like to limit:

Dice dice = 0; // warning not compile
Dice dice = 1;
Dice dice = 2;
Dice dice = 3;
Dice dice = 4;
Dice dice = 5;
Dice dice = 6;
Dice dice = 7; // warning not compile

Like:

typedef Dice = 1|2|3|4|5|6

Is it possible in Dart somehow?

lolelo
  • 698
  • 6
  • 18
  • 2
    Not possible in Dart. I would suggest using an `enum` instead of if you want to limit a variable to a limited set of values. – julemand101 Nov 12 '22 at 16:38
  • Dart does not literally support this, but it can be done using a suitable class. – Ber Dec 07 '22 at 22:46

2 Answers2

1

You can create a class that takes a set of allowed values and throws and exception if a value not in the set is assigned to its value member:

class Restricted<T> {
  late final Set<T> _validSet;

  late T _value;

  Restricted(Set<T> validSet) {
    _validSet = Set<T>.unmodifiable(validSet);
  }

  T get value => _value;

  set value(T newValue) {
    if (!_validSet.contains(newValue)) {
      throw RangeError('$newValue is not a valid value');
    }

    _value = newValue;
  }
}

And use it like

var r = Restricted<int>({1,2,3,4,5,6});

r.value = 2;  // Okay
r.value = 0;  // throws ValueError

See the code in action on DartPad

Ber
  • 40,356
  • 16
  • 72
  • 88
  • That's in runtime. But I hoped to get IDE warnings and not able to compile – lolelo Dec 08 '22 at 11:07
  • @lolelo For compile time, use an Enum class. – Ber Dec 08 '22 at 11:35
  • Do you mean the generic `T` as enum, or the class `Restricted` could be Enum? – lolelo Dec 08 '22 at 15:59
  • @lolelo I mean to use an `Enum` the way it is intended to be used: A value from a fixed set of options. Since Dart does not support restricted scalar (int) types, this may the the solution you need. It even offers the benefit of having named, printable values. Check it out: https://api.dart.dev/be/180791/dart-core/Enum-class.html – Ber Dec 09 '22 at 15:33
  • It could be restricting values to certain string values, like names. or only allowing certain double values, like person weights in certain values, person length to be 1.10, 1.20, 1.30.... Yes in Dart it seems to be limited to Enum in this. It's a language based feature question. In the question my code example is a example. – lolelo Dec 10 '22 at 11:41
0

You are asking about a possible solution you have in mind, without sharing the actual problem.

If you state you real problem in more general terms, you may find a better answer here. Maybe an Enum is a better fit than a restricted int.

Ber
  • 40,356
  • 16
  • 72
  • 88