Skip to content

IIFE type inference #2820

@modulovalue

Description

@modulovalue

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

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

class Foo<T> {
  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: #2820 (comment)

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problemstype-inferenceType inference, issues or improvements

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions