类型别名

类型别名——通常称为 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 = {}; // 冗长。
ListMapper<String> m2 = {}; // 同上,但更短更清晰。

在大多数情况下,我们建议使用 内联函数类型 代替函数的 typedef。 但是,函数 typedef 仍然很有用:

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!
}