You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
then T is Object. I can see why - it's the nearest possible supertype of both int and String. Unfortunately for my case, this is not what I wanted. I was hoping to restrict my fuction so that if the first argument was an int, the second argument is also an int.
I can see that Dart's behaviour here is not in any way wrong, but I'm curious to know why this choice was made, and whether there is a way to change the behaviour to get the effect I wanted.
Just by way of comparison, TypeScriptdoes behave the way I had hoped:
functionmyFunc<T>(arg1: T,arg2: T): T{returnarg1;}constz=myFunc(1asnumber,"");// Error: Argument of type 'string' is not assignable to parameter of type 'number'classA{f1(){};}classB{f2(){};}consta=myFunc(newA(),newB());// Error: Argument of type 'B' is not assignable to parameter of type 'A'.
What is Dart's justification for its behaviour, and are there situations where this is advantageous? Can I force it to behave otherwise?
The text was updated successfully, but these errors were encountered:
I was hoping to restrict my fuction so that if the first argument was an int, the second argument is also an int.
Can I force it to behave otherwise?
If you want the two arguments to be exactly the same type, you'll have to emulate invariance as described in #3156 (comment).
But depending on your use case, adding a subclass constraint might also be satisfactory:
AmyFunc<A, BextendsA>(A input1, B input2) {
return input1;
}
Now when you write
final x =myFunc(123, "hello");
you get
Couldn't infer type parameter 'B'.
Tried to infer 'String' for 'B' which doesn't work:
Type parameter 'B' is declared to extend 'A' producing 'int'.
The type 'String' was inferred from:
Parameter 'input2' declared as 'B'
but argument is 'String'.
Consider passing explicit type argument(s) to the generic.
Consider this function:
If I call this function like so:
then
T
isint
, but if I call it like this:then
T
isObject
. I can see why - it's the nearest possible supertype of bothint
andString
. Unfortunately for my case, this is not what I wanted. I was hoping to restrict my fuction so that if the first argument was anint
, the second argument is also anint
.I can see that Dart's behaviour here is not in any way wrong, but I'm curious to know why this choice was made, and whether there is a way to change the behaviour to get the effect I wanted.
Just by way of comparison,
TypeScript
does behave the way I had hoped:What is Dart's justification for its behaviour, and are there situations where this is advantageous? Can I force it to behave otherwise?
The text was updated successfully, but these errors were encountered: