Dart: Typedef

Carlos Costa

In brief: Typedefs are a way to customize the type system of Dart. They are used to define function types and class types.

Example:

typedef IntList = List<int>;
typedef StringMap = Map<String, String>;

IntList list = [1, 2, 3];
StringMap map = {'name': 'Jack', 'age': '25'};

print(list); // [1, 2, 3]
print(map); // {name: Jack, age: 25}

We can also use typedefs to define function types:

typedef StringCallback = void Function(String);

void main() {
  StringCallback callback = (String name) {
    print('Hello $name');
  };

  callback('Jack'); // Hello Jack
}

Another example using function types:

typedef Calc = int Function(int, int);

Calc sum = (int a, int b) => a + b;
Calc sub = (int a, int b) => a - b;

Typedef can be used with classes too:

typedef StringMap = Map<String, String>;

class Person {
  final StringMap data;

  Person(this.data);

  String get name => data['name'];
  String get age => data['age'];
}

void main() {
  final person = Person({'name': 'Jack', 'age': '25'});

  print(person.name); // Jack
  print(person.age); // 25
}

We can combine typedef with generics:

typedef Calc<T, K> = T Function(K, K);

void main(List<String> args) {
  Calc<int, int> sum = (a, b) => a + b;
  Calc<int, int> sub = (a, b) => a - b;
  Calc<double, double> mul = (a, b) => a * b;
  Calc<double, double> div = (a, b) => a / b;
}

References