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:
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {
compare = f;
}
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
// All we know is that compare is a function,
// but what type of function?
assert(coll.compare is Function);
}
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.
typedef Compare = int Function(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}
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:
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!
}