Skip to main content

avoid-unrelated-type-casts

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() {
// LINT: Avoid unrelated 'as' cast. Target type has no overlap with the cast type.
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) {}
}
}

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

Known Limitations

The rule does not have access to all subclasses and their mixins and therefore in some cases will highlight such usages as incorrect.

class Parent {}

mixin Mixin {}

class Child with Mixin {}

void fn() {
final list = <Parent>[]; // List of 'Parents'

for (final item in list) {
(item as Mixin); // Expected
}
}

Additional Resources