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'.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With