Skip to main content

avoid-unnecessary-type-assertions

added in: 1.6.0
Pro+
preset: recommended

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() {
final result = myList is List<int>; // LINT: Avoid unnecessary 'is' assertion. The result is always 'true'.
myList.whereType<int>(); // LINT: Avoid unnecessary 'whereType<int>()' assertion.

final animal = Animal();

if (animal case Animal result) {} // LINT: Avoid unnecessary 'case' assertion. The result is always 'true'.
if (animal case Animal()) {} // LINT: Avoid unnecessary 'case' assertion. The result is always 'true'.
}
}

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()) {}
}
}

Additional Resources