Skip to content

Infer most specific generic type for methods #1557

Open
@renggli

Description

@renggli

The following example works as expected:

class Clazz<T> {}

Clazz<T> join<T>(Clazz<T> a, Clazz<T> b) => Clazz<T>();

void main() {
  final a = Clazz<int>();
  final b = Clazz<double>();
  print(join(a, b));  // 'Clazz<num>' 👍
}

The problem I am facing is that I cannot figure out a way to write an (operator) method within Clazz that works and that doesn't yield Clazz<dynamic> as a result.

I would have expected that the following static extension method is very similar to the function above, yet the compiler is unable to infer R as num in this case and yields The argument type 'Clazz<double>' can't be assigned to the parameter type 'Clazz<int>':

class Clazz<T> {}

extension ClazzExt<R> on Clazz<R> {
  Clazz<R> join(Clazz<R> other) => Clazz<R>();
}

void main() {
  final a = Clazz<int>();
  final b = Clazz<double>();
  print(a.join(b));  // The argument type 'Clazz<double>' can't be assigned to the 
                     // parameter type 'Clazz<int>_ 👎 
}

Context: https://stackoverflow.com/questions/66851159/getting-a-more-specific-generic-type-than-dynamic

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions