Typedef in Dart

What is Typedef?

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.

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

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.

Use explicit names and retain type information:

// 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
}

Because typedef are simply aliases, they offer a way to check the type of any function.

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 :

  1. a type annotation,
  2. as a return type or
  3. parameter type in a function declaration,
  4. in a function type, a
  5. s a type argument,
  6. in a type test,
  7. in a type cast,
  8. and in an on clause of a try statement.