Skip to content

Type inference from parameter type #37247

@derolf

Description

@derolf

The problem

Consider the following example:

    typedef Action<T> = void Function(T arg);
    
    void execute<T>(T arg, Action<T> action) => action(arg);
    
    void main() {
      execute(42, (value) => print(value.bar));
    }

I would expect the Dart Analyzer to fail at value.bar since T could be inferred to number. Instead, Dart does not infer T to number, but falls back to dynamic.

What are other languages doing?

Equivalent example in TypeScript:

    type Action<T> = (arg: T) => void;
    
    function execute<T>(arg: T, action: Action<T>) {
        return action(arg);
    }
    
    function main() {
      execute(42, (value) => console.log(value.bar));
    }

yields error

Property 'bar' does not exist on type 'number'.

Equivalent example in Kotlin:

    typealias Action<T> = (arg: T) -> Unit;
    
    fun<T> execute(arg: T, action: Action<T>) = action(arg);
    
    fun main() {
      execute(42) { value -> print(value.bar) };
    }

yields error

Unresolved reference: bar

https://stackoverflow.com/questions/56540905/type-inference-from-parameter-type

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions