always_ specify_ types
Details about the 'always_specify_types' diagnostic produced by the Dart analyzer.
Missing type annotation.
Description
#The analyzer produces this diagnostic when an explicit type annotation is missing.
This includes in the following cases:
-
A variable declaration that uses
var,final, orconstwithout a specific type. - A function parameter lacks a type annotation.
- A collection literal lacks explicit type arguments.
- A reference to a generic class, mixin, or enum lacks type arguments.
Types annotated with @optionalTypeArgs from package:meta are
exempt from requiring type arguments.
Examples
#
The following code produces this diagnostic because
the top-level variable uses var without an explicit type:
var x = 1;
The following code produces this diagnostic because
the parameter p lacks a type annotation:
void f(p) {}
The following code produces this diagnostic because the set literal lacks an explicit type argument:
Set<int> items = {1, 2};
The following code produces this diagnostic because
the generic type C is used without specifying its type argument:
class C<T> {}
C c = C<int>();
Common fixes
#Add an explicit type annotation to variable declarations:
int x = 1;
Add a type annotation to parameters:
void f(int p) {}
Add explicit type arguments to collection literals:
Set<int> items = <int>{1, 2};
Add type arguments to generic type references:
class C<T> {}
C<int> c = C<int>();
If a type argument is meant to be optional,
annotate the declaration with @optionalTypeArgs from
package:meta to exempt it from this lint:
import 'package:meta/meta.dart';
@optionalTypeArgs
class C<T> {}
C c = C();
Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Report an issue.