Skip to content

cast_to_own_type

Reports cast<T>() of a collection or a stream to the type arguments it already has. Use the value as it is.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
deletes the call

cast<T>() of a collection or a stream to exactly the type arguments it has: names.cast<String>() on a List<String>. Only a value whose static type is a class of dart:core, dart:collection or dart:async is judged.

It does not report:

  • a cast to another type, even a wider one: cast<Object>() changes the static type;
  • a cast of a dynamic value;
  • a cast of a class of the code itself.

A cast of one value, name as String, is the analyzer’s warning unnecessary_cast.

The cast wraps the value in a view that checks every element against a type all of them already have, and gives back the same static type.

Violating
List<String> texts(List<String> names) => names.cast<String>();
Corrected
List<String> texts(List<String> names) => names;

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:

// The view keeps the checks of the list a plugin hands back.
// ignore: assay/cast_to_own_type

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