Skip to main content

avoid-unnecessary-type-casts

Warns about unnecessary use of the as operator and cast method.

Unnecessary type casts 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 main() {
// LINT: Avoid unnecessary 'as' type cast.
final result = myList as List<int>;

final animal = Animal();
// LINT: Avoid unnecessary 'as' type cast.
if (animal case HomeAnimal() as Animal) {}
}
}

class Animal {}

class HomeAnimal extends Animal {}

✅ Good:

class Example {
final myList = <int>[1, 2, 3];

void main() {
final result = myList;

final animal = Animal();
if (animal case HomeAnimal()) {}
}
}

Additional Resources