Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make T extends two types?

Tags:

dart

void foo<T extends num, String> (T t) {
  if (t is String) {
    String s = t; // Error
  }
}

A value of type 'T' can't be assigned to a variable of type 'String'.

like image 291
iDecode Avatar asked Feb 13 '26 12:02

iDecode


1 Answers

You won't be able to do this with base Dart as your generic type T can only extends one class. The only way I would see such a behavior feasible would be by using a 3rd party packages such as dartz with its Either type.

Example

void foo<T extends num>(Either<T, String> t) {
  final String s;
  if (t.isRight()) {
    s = (t as Right<T, String>).value;
  } else {
    s = (t as Left<T, String>).value.toStringAsFixed(3);
  }
  print(s);
}

foo(Left(1.0)); // prints '1.000'
foo<int>(Right('bar')); // prints 'bar'
like image 108
Guillaume Roux Avatar answered Feb 16 '26 06:02

Guillaume Roux