跳至主要內容

Typedefs (類型別名)

類型別名 (type alias) — 通常稱為 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.

我們建議在大多數情況下,使用inline function types (行內函式類型) 而不是 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!
}