always_specify_types
指定类型注解。
详细信息
#应该指定类型注解。
当类型未知时,避免使用 var 以及省略类型注解的简写。如果明确表明类型未知,请使用 dynamic。如果明确表明需要一个实现了 == 和 hashCode 的对象,请使用 Object。
差
dart
var foo = 10;
final bar = Bar();
const quux = 20;好
dart
int foo = 10;
final Bar bar = Bar();
String baz = 'hello';
const int quux = 20;注意:使用 meta 包中的 @optionalTypeArgs 注解,API 作者可以特殊处理那些类型需要是 dynamic 但其声明应视为可选的类型参数。例如,假设你有一个 Key 对象,其类型参数你想视为可选。使用 @optionalTypeArgs 将会是这样
dart
import 'package:meta/meta.dart';
@optionalTypeArgs
class Key<T> {
...
}
void main() {
Key s = Key(); // OK!
}不兼容的规则
#always_specify_types 规则与以下规则不兼容
avoid_types_on_closure_parametersomit_local_variable_typesomit_obvious_local_variable_typesomit_obvious_property_types
启用
#要启用 always_specify_types 规则,请在你的 analysis_options.yaml 文件中的 linter > rules 下添加 always_specify_types
analysis_options.yaml
yaml
linter:
rules:
- always_specify_types如果你改为使用 YAML 映射语法配置 linter 规则,请在 linter > rules 下添加 always_specify_types: true
analysis_options.yaml
yaml
linter:
rules:
always_specify_types: true