Typedefs

In Dart, functions are objects, just like strings and numbers areobjects. A typedef, or function-type alias, gives a function type aname that you can use when declaring fields and return types. A typedefretains type information when a function type is assigned to a variable.

Consider the following code, which doesn’t use a typedef:

  1. class SortedCollection {
  2. Function compare;
  3. SortedCollection(int f(Object a, Object b)) {
  4. compare = f;
  5. }
  6. }
  7. // Initial, broken implementation.
  8. int sort(Object a, Object b) => 0;
  9. void main() {
  10. SortedCollection coll = SortedCollection(sort);
  11. // All we know is that compare is a function,
  12. // but what type of function?
  13. assert(coll.compare is Function);
  14. }

Type information is lost when assigning f to compare. The type off is (Object, Object)int (where → means returns), yet thetype of compare is Function. If we change the code to use explicitnames and retain type information, both developers and tools can usethat information.

  1. typedef Compare = int Function(Object a, Object b);
  2. class SortedCollection {
  3. Compare compare;
  4. SortedCollection(this.compare);
  5. }
  6. // Initial, broken implementation.
  7. int sort(Object a, Object b) => 0;
  8. void main() {
  9. SortedCollection coll = SortedCollection(sort);
  10. assert(coll.compare is Function);
  11. assert(coll.compare is Compare);
  12. }

Note: Currently, typedefs are restricted to function types. We expect this to change.

Because typedefs are simply aliases, they offer a way to check the typeof any function. For example:

  1. typedef Compare<T> = int Function(T a, T b);
  2. int sort(int a, int b) => a - b;
  3. void main() {
  4. assert(sort is Compare<int>); // True!
  5. }