别名

10 阅读1分钟

一个声明和使用名为IntList的类型别名的示例:

typedef IntList = List<int>;
IntList il = [1, 2, 3];

类型别名可以有类型参数:

typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.

在大多数情况下,建议对函数使用内联函数类型而不是typedef。但是,函数typedefs仍然有用:

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