dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
627 stars 172 forks source link

Add warning/lint for `Iterable<E>.whereType<T>` when `T is! E` #4875

Open osaxma opened 4 months ago

osaxma commented 4 months ago

Add warning for Iterable<E>.whereType<T> when T is! E.

I think the static analyzer should warn against such obvious cases:

void main() {
  var some = <int>[].whereType<String>();  // no warning here
  print(some.isEmpty); // always true 
}

I expected to have a warning along the lines: Unnecessary Iterable; 'Iterable<int>' can never contain type 'String'...

Why this is useful?

I believe many developers, including myself, relay on the static analyzer when refactoring code by slightly modifying a program so analysis errors/warnings are propagated throughout the codebase to guide the refactoring effort. In such cases, it would be useful to catch the case above, which I came across today.

lrhn commented 4 months ago

Sounds like something that can be included in https://dart.dev/tools/linter-rules/collection_methods_unrelated_type I'll transfer this request to the linter repo.

osaxma commented 4 months ago

CL submitted at: https://dart-review.googlesource.com/c/sdk/+/351781 to include the lint in collection_methods_unrelated_type