类型别名
类型别名(通常称为 typedef,因为它使用关键字 typedef
声明)是引用类型的一种简洁方式。以下是声明和使用名为 IntList
的类型别名的示例
dart
typedef IntList = List<int>;
IntList il = [1, 2, 3];
类型别名可以有类型参数
dart
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.
在大多数情况下,我们建议为函数使用内联函数类型而不是 typedefs。然而,函数 typedefs 仍然可能有用
dart
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!
}