Typedef is an alias for creating variables of New Types or instances of Function objects.

typedefs can be used to achieve type annotations. Typedef allows you to do the following new things

  • Create a variable of new types similar to a normal variable declaration
  • You can pass new types to functions
  • Functions can return these types
  • You can create Instances of new Function types
  • Assign the instance of function types with functions

Dart typedef examples

The Typedef keyword is used to create a new custom type or instance of a Function class.

Here is a syntax

typedef newtype= Types or function // new syntax
typedef Types or Function expression; // Old Syntax.

In the older version syntax, Type is omitted and variable is required.

Examples are below

typedef function(arguments)
typedef  variable= function
  • Custom Type: let’s create a new type
typedef StringList = List<String>;

You can use the new type to create a variable or pass arguments, returns in a function

typedef StringList = List<String>;

void main() {
  StringList strs = ["one", "two", "three"];

  print(strs); // 18
}

StringList printStrings(StringList strs) {
  print(strs); // 18
  return strs;
}
  • Instance of Function class

Let’s create a new Function type using typedef.

typedef Calculator(int first, int second);

You can create a variable of these and assign the functions.

typedef Calculator(int first, int second);

sum(int m, int n) {
  print("Result of Sum: ${m + n}");
}

void main() {
  Calculator add = sum;
  add(10, 20);
}