The purpose of typedef is to create an alias name for another data type.
A type alias declares a name for a type expression
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types.
A typedef retains type information when a function type is assigned to a variable.
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {
compare = f;
}
}
int sort(Object a, Object b) {
return 0;
}
main() {
SortedCollection collection = SortedCollection(sort);
assert(collection.compare is Function);
}
Note : Type information is lost when assigning f to compare.
// give a function type a name or alias name
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); //true
assert(coll.compare is Compare); // true
}
Example
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
print(sort is Compare<int>); // true!
}
A type alias can be used as :