Skip to content

impossible_type_test

Reports a type test or cast that no value can pass. Fix the type that changed, or delete the dead check.

Tier
blocking
Scope
Dart
Lowest preset
recommended
Fix
none

A type test or a cast that no value can pass:

  • an is that is always false, or an is! that is always true;
  • an as that always throws;
  • a whereType or cast of an iterable whose elements can never have the type named.

The violation is on the test or the cast, or on the method’s name for whereType and cast.

Two unrelated types are not enough, since a third class can implement both. The rule reports only where one side is closed: String, bool, int, double, or an enum that is not generic. A value of a closed type has another type only if that type is one of its supertypes. A value of another type has a closed type only if the closed type is a subtype of it.

It does not report:

  • int against double, since on the web every number is both;
  • a type variable, an extension type, FutureOr, dynamic, Null, a function type or a record;
  • a test where both sides can be null, which null passes;
  • a test that is always true (the analyzer’s unnecessary_type_check), or a pattern that never matches (the analyzer’s pattern_never_matches_value_type).

A test that can never pass means the code believes in a case that cannot happen. Usually the type of the value changed (a field that was Object, an argument that came from JSON) and the check stayed behind. The branch it guards is dead, and such a cast throws on every run.

Violating
void show(int count) {
if (count is String) print('never');
}
Corrected
void show(Object count) {
if (count is String) print(count);
}

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression, which goes above the line of the test:

// The check stays until the old String counts are migrated.
// ignore: impossible_type_test
if (count is String) print(count);

// ignore_for_file: assay/impossible_type_test silences it in a whole file, and // ignore: assay/impossible_type_test with the prefix works too. See Suppressions.