dart-lang / dart-lang/language

Type inference seems to prioritize outer type information over inner type information. Is this intended?

Open
#2,863 3 comments 0 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Hi there, this bug is coming out of a discussion with @vsmenon. I experienced some behavior that is surprising to me and wanted to check if this is intended.

The test case is this: https://dartpad.dev/?id=cff671cf94e99f93e809a2ecfeed8d20

```dart
class Getter {}

T get(Getter getter) {
if (T == int) {
return 42 as T;
} else if (T == String) {
return "the answer to life, the universe, and everything" as T;
}
throw "Unexpected type: ${T.toString()}";
}

void main() {
var intGetter = Getter();
var strGetter = Getter();

// This works:
var intVal = get(intGetter); // inferred as get
print(intVal);
var strVal = get(strGetter); // inferred as get
print(strVal);

// This doesn't work, T is resolved to Object? (the argument
// type of print()).
//
// But that is confusing because we are passing a Getter,
// not a Getter.
print(get(intGetter)); // inferred as get
}
```

The output is:

```
42
the answer to life, the universe, and everything
Uncaught Error: Unexpected type: Object?
```

I would have expected `print(get(intGetter));` to resolve to `get`, to match the behavior of `var intVal = get(intGetter);`. But instead the expected return type of `Object?` took higher priority.

Is this expected?

Contributor guide

Open the contributing guide

Research direction

Start by running the linked DartPad reproduction and compare the inferred types for get(intGetter) assigned to var versus nested in print(get(intGetter)). Read the Dart language type-inference specification and the issue discussion; done means establishing whether the behavior is intended and, if not, defining the language change needed.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.