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;

4. SortedCollection(int f(Object a, Object b)) {
5. compare = f;
6. }
7. }

9. // Initial, broken implementation.
10. int sort(Object a, Object b) => 0;

12. void main() {
13. SortedCollection coll = SortedCollection(sort);

15. // All we know is that compare is a function,
16. // but what type of function?
17. assert(coll.compare is Function);
18. }

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);

3. class SortedCollection {
4. Compare compare;

6. SortedCollection(this.compare);
7. }

9. // Initial, broken implementation.
10. int sort(Object a, Object b) => 0;

12. void main() {
13. SortedCollection coll = SortedCollection(sort);
14. assert(coll.compare is Function);
15. assert(coll.compare is Compare);
16. }

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);

3. int sort(int a, int b) => a - b;

5. void main() {
6. assert(sort is Compare<int>); // True!
7. }