dart-lang / dart-lang/language

IIFE type inference

Open
#2,820 9 comments 1 reaction 0 assignees View on GitHub
feature type-inference
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Consider the following program that does not compile because type inference fails to infer `Foo` as the type of the immediately invoked function expression (IIFE):

```dart
void main() {
>[
Foo(),
// Error: A value of type 'Foo' can't be assigned to a variable of type 'Foo'.
// - 'Foo' is from 'package:dartpad_sample/main.dart' ('lib/main.dart').
// }(),
// ^
// Error: Compilation failed.
(){
return Foo();
}(),
];
}

class Foo {
Foo();
}
```

I find IIFEs to be very useful because they allow me to not pollute scopes with names that don't need to be there. I regularly experience type inference issues related to IIFEs. I think it would be great if Dart could have better support for IIFE type inference.

Edit:
See also: https://github.com/dart-lang/language/issues/2820#issuecomment-1431253037

_Edit: I think that this issue applies to all function literals (i.e. `() {}`, `() sync* {}`, ` () async {}` and `() async* {}` because it doesn't look like the type checker needs to depend on their evaluation strategy._

Contributor guide

Open the contributing guide

Research direction

Start with the reproducing Dart program in the issue and compare the inferred types for the list literal, constructor call, and immediately invoked function expression. Read the linked discussion comment and the follow-up covering synchronous and asynchronous function literals. Done means the intended contextual type is inferred consistently for the listed IIFE forms without the reported assignment error.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.