omit_obvious_property_types

Unreleased
Fix available

Omit obvious type annotations for top-level and static variables.

Details

#

Don't type annotate initialized top-level or static variables when the type is obvious.

BAD:

dart
final int myTopLevelVariable = 7;

class A {
  static String myStaticVariable = 'Hello';
}

GOOD:

dart
final myTopLevelVariable = 7;

class A {
  static myStaticVariable = 'Hello';
}

Sometimes the inferred type is not the type you want the variable to have. For example, you may intend to assign values of other types later. You may also wish to write a type annotation explicitly because the type of the initializing expression is non-obvious and it will be helpful for future readers of the code to document this type. Or you may wish to commit to a specific type such that future updates of dependencies (in nearby code, in imports, anywhere) will not silently change the type of that variable, thus introducing compile-time errors or run-time bugs in locations where this variable is used. In those cases, go ahead and annotate the variable with the type you want.

GOOD:

dart
final num myTopLevelVariable = 7;

class A {
  static String? myStaticVariable = 'Hello';
}

This rule is experimental. It is being evaluated, and it may be changed or removed. Feedback on its behavior is welcome! The main issue is here: https://github.com/dart-lang/linter/issues/5101.

Incompatible rules

#

The omit_obvious_property_types rule is incompatible with the following rules:

Enable

#

To enable the omit_obvious_property_types rule, add omit_obvious_property_types under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:
  rules:
    - omit_obvious_property_types

If you're instead using the YAML map syntax to configure linter rules, add omit_obvious_property_types: true under linter > rules:

analysis_options.yaml
yaml
linter:
  rules:
    omit_obvious_property_types: true