avoid-unnecessary-type-assertions
Warns about unnecessary usage of the is
operator, and whereType
and whereNotNull
methods.
Unnecessary type assertions are either a sign of a bug (another type should be used instead or the type hierarchy should include the expected type) or are redundant and can simply be removed.
Example
❌ Bad:
class Example {
final myList = <int>[1, 2, 3];
void fn() {
// LINT: Avoid unnecessary 'is' assertion. The result is always 'true'.
final result = myList is List<int>;
// LINT: Avoid unnecessary 'whereType<int>()' assertion.
myList.whereType<int>();
final animal = Animal();
// LINT: Avoid unnecessary 'case' assertion. The result is always 'true'.
if (animal case Animal result) {}
// LINT: Avoid unnecessary 'case' assertion. The result is always 'true'.
if (animal case Animal()) {}
}
}
class Animal {}
class HomeAnimal extends Animal {}
✅ Good:
class Example {
final myList = <int?>[1, 2, 3, null];
void fn() {
myList.whereType<int>(); // Correct, filters non-null values
final animal = Animal();
if (animal case HomeAnimal result) {} // Correct, checks for a subclass
if (animal case HomeAnimal()) {}
}
}