Skip to main content

avoid-inferrable-type-arguments

added in: 1.11.0
⚙️🛠
Pro+
preset: recommended

Warns when an inferrable type argument can be removed without affecting the code.

Adding type arguments to some expressions is usually unnecessary, since the type can be inferred from the context of the expression.

This rule mostly covers return statements, method invocations and collection literals.

warning

This rule is not compatible with prefer-explicit-type-arguments.

⚙️ Config

Set ignored-invocations (default is empty) to ignore type arguments of a specific invocation (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-inferrable-type-arguments:
ignored-invocations:
- context.read
- GetIt.I
- watch

Example

❌ Bad:

void main() {
withList(<num>[1]); // LINT: Avoid inferrable type arguments. Try removing type arguments.

final List<int>? nullableList = null;
withList(nullableList ?? <num>[1]); // LINT: Avoid inferrable type arguments. Try removing type arguments.
withList(nullableList == null ? <num>[1] : <num>[2]); // LINT: Avoid inferrable type arguments. Try removing type arguments.

withGenericList(<String>['1']); // LINT: Avoid inferrable type arguments. Try removing type arguments.

withList(withGenericList<num>([1])); // LINT: Avoid inferrable type arguments. Try removing type arguments.
withList(onlyParam<String>('1')); // LINT: Avoid inferrable type arguments. Try removing type arguments.
}

void withList(List<num> items) {}

List<T> withGenericList<T>(List<T> items) => items;

List<num> onlyParam<P>(P param) => [1];

✅ Good:

void main() {
withList(<int>[1]);
withList([1]);

final List<int>? nullableList = null;
withList(nullableList ?? [1]);
withList(nullableList == null ? [1] : [2]);

withGenericList(['1']);

withList(withGenericList([1]));
withList(onlyParam('1'));
}

void withList(List<num> items) {}

List<T> withGenericList<T>(List<T> items) => items;

List<num> onlyParam<P>(P param) => [1];

Example with "ignored-invocations"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-inferrable-type-arguments:
ignored-invocations:
- context.read

✅ Good:

void fn(BuildContext context) {
withList(context.read<int>()); // Correct, ignored
}