類型定義 (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.
我們建議在大多數情況下使用內嵌函式類型來取代函式的類型定義。然而,函式類型定義仍然很有用
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!
}
除非另有說明,本網站上的文件反映的是 Dart 3.6.0 版本。頁面最後更新於 2024-12-10。 檢視原始碼 或 回報問題。