Skip to content

Infer the type of an optional parameter from the default value #3970

Open
@eernstg

Description

@eernstg

@lrhn proposed this feature in a particular context. I think it's both useful and Darty, and we should consider the proposal in a more general form. Here we go:

Consider a named or positional optional parameter p with an explicit default value, but no type annotation and no inferred declared type from override inference. The declared type of p is then inferred to be the static type of its default value.

Apart from convenience and conciseness, the fact that variable declarations can have their type inferred from an initializing expression also serves to motivate this feature.

Note that this proposal, like override inference, will benefit from a strict treatment of the type dynamic: We want to have typed parameters, so we want to get a head-up whenever a missing type causes dynamic to be inferred by default. When this kind of checking is in place, we can trust every optional parameter with a default value but no visible declared type to have obtained an appropriate declared type by inference.

For example:

void foo([i = 10]) {} // Inferred as `int i = 10`.

abstract class A {
  void bar1({num name});
  void bar2();
}

class B extends A {
  void bar1({name = 10}) {} // Inferred as `num name = 10`, by override inference.
  void bar2({name = 10}) {} // Inferred as `int name = 10`, using this feature.
  void qux({name}) {} // Inferred as `dynamic name = null`, using older rules; could be linted.
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    small-featureA small feature which is relatively cheap to implement.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions