Skip to main content

avoid-unrelated-type-casts

added in: 1.0.0
Pro+
preset: recommended

Warns about unrelated usages of the as operator and cast method.

Incorrect usages of the as operator can lead to runtime exceptions and unexpected behavior.

Example

❌ Bad:

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

final Animal animal = Animal();

void main() {
final result = regularString as int; // LINT: Avoid unrelated 'as' cast. Target type has no overlap with the cast type.
final result2 = myList as List<String>; // LINT: Avoid unrelated 'as' cast. Target type has no overlap with the cast type.

final result3 = animal as NotAnimal; // LINT: Avoid unrelated 'as' cast. Target type has no overlap with the cast type.

if (animal case Animal() as NotAnimal) {} // LINT: Avoid unrelated 'as' cast. Target type has no overlap with the cast type.
}
}

class Animal {}

class HomeAnimal extends Animal {}

class NotAnimal {}

✅ Good:

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

final Animal animal = Animal();

void main() {
final result = regularString;
final result2 = myList;

final result3 = animal;

if (animal case Animal() as HomeAnimal) {}
}
}

Additional Resources