flutter
/

Dart Typedef – Type Aliases for Functions and Types

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Typedef – Type Aliases for Functions and Types

What is a Typedef?

A typedef (type definition) creates an alias for a type, especially useful for function types. It allows you to give a meaningful name to a function signature, making your code more readable and easier to maintain. Since Dart 2.13, typedefs can also be generic, enabling you to create reusable type aliases with type parameters.

Why Use Typedefs?

    • Readability – a well‑named alias makes code self‑documenting.
    • Reusability – define a function signature once and use it in many places.
    • Maintainability – change the signature in one place and all uses update.
    • Generic support – create generic callbacks that work with any type.

Basic Typedef for a Function

Define a typedef using the typedef keyword followed by a name and the function type signature. Then use the alias as a type annotation.

DARTRead-only
1
typedef IntOperation = int Function(int a, int b);

int add(int a, int b) => a + b;
int multiply(int a, int b) => a * b;

void main() {
  IntOperation operation = add;
  print(operation(5, 3)); // 8

  operation = multiply;
  print(operation(5, 3)); // 15
}

Old Syntax (Pre‑Dart 2.13)

Before Dart 2.13, typedefs were defined using the old syntax, which is still valid but less flexible. The new syntax (using =) is preferred for clarity and generic support.

DARTRead-only
1
// Old syntax (still works)
typedef IntOperationOld = int Function(int a, int b);

// Using the old alias is identical

Generic Typedefs

With Dart 2.13 and later, you can create generic typedefs. This is extremely powerful for creating reusable callbacks and transformers.

DARTRead-only
1
typedef Transformer<T> = T Function(T value);

int square(int x) => x * x;
String toUpper(String s) => s.toUpperCase();

void main() {
  Transformer<int> intTransform = square;
  print(intTransform(5)); // 25

  Transformer<String> stringTransform = toUpper;
  print(stringTransform('hello')); // HELLO
}

Using Typedefs as Callback Types

Typedefs shine when you have functions that accept callbacks. The alias documents what kind of callback is expected.

DARTRead-only
1
typedef OnSuccess<T> = void Function(T data);
typedef OnError = void Function(String message);

void fetchData(OnSuccess<String> onSuccess, OnError onError) {
  // Simulate network call
  bool success = true;
  if (success) {
    onSuccess('Data loaded');
  } else {
    onError('Network error');
  }
}

void main() {
  fetchData(
    (data) => print('Success: $data'),
    (error) => print('Error: $error'),
  );
}

Typedef for Generic Collections

While less common, you can also alias regular types. This can simplify complex type names.

DARTRead-only
1
typedef IntMap = Map<String, int>;

void main() {
  IntMap scores = {'Alice': 95, 'Bob': 87};
  print(scores); // {Alice: 95, Bob: 87}
}

Typedefs with Named Parameters

You can define typedefs that include named parameters. This makes the callback more self‑documenting.

DARTRead-only
1
typedef DataHandler = void Function({required String name, int? age});

void process(DataHandler handler) {
  handler(name: 'Alice', age: 30);
}

void main() {
  process(({required String name, int? age}) {
    print('Name: $name, Age: $age');
  });
}

Best Practices

    • Use meaningful names that describe the purpose (e.g., StringTransformer, ErrorCallback).
    • Prefer generic typedefs over duplicating similar signatures.
    • Use the new syntax (=) for clarity and future‑proofing.
    • Keep typedefs in a dedicated file if they are shared across many modules.
    • Document the expected behavior of the function alias.

Key Takeaways

    • typedef creates an alias for a type, especially function types.
    • Since Dart 2.13, typedefs can be generic, allowing reusable type aliases.
    • Typedefs improve readability and maintainability of callbacks.
    • They can include named parameters and be used for regular types too.
    • Use the modern syntax: typedef Name = Type;.

Try it yourself

typedef StringTransformer = String Function(String input);

String toUpper(String s) => s.toUpperCase();
String reverse(String s) => s.split('').reversed.join();

void main() {
  StringTransformer transformer = toUpper;
  print(transformer('hello')); // HELLO

  transformer = reverse;
  print(transformer('hello')); // olleh
}

Test Your Knowledge

Q1
of 4

What is the purpose of a typedef in Dart?

A
To define a new type that extends an existing class
B
To create an alias for a type, especially function types
C
To import a library
D
To declare a constant
Q2
of 4

How do you define a generic typedef for a function that takes a T and returns a T?

A
typedef Identity<T> = T Function(T);
B
typedef Identity = T Function<T>(T);
C
typedef Identity(T) = T Function(T);
D
typedef Identity = T Function(T) where T;
Q3
of 4

Which syntax is recommended for typedefs in Dart 2.13+?

A
typedef Name = FunctionType;
B
typedef Name FunctionType;
C
alias Name = FunctionType;
D
type Name = FunctionType;
Q4
of 4

Can a typedef include named parameters?

A
Yes
B
No
C
Only positional parameters
D
Only required parameters

Frequently Asked Questions

What is the difference between the old and new typedef syntax?

Old syntax: typedef IntOperation = int Function(int a, int b); (pre‑Dart 2.13). New syntax (Dart 2.13+) is essentially the same but allows generics and is clearer. The old syntax is still supported but the new one is recommended.

Can I create a typedef for a generic function that returns a Future?

Yes. For example: typedef AsyncCallback<T> = Future<T> Function(T value);. This allows you to define asynchronous callbacks.

Are typedefs just for functions?

No, they can alias any type, but they are most useful for function types. You can alias complex generic types like Map<String, List<int>> to a shorter name.

Can I use a typedef inside a class?

Yes, typedefs can be defined at the top level or inside a class (though it's less common). When defined inside a class, they are scoped to that class.

How do I use a typedef with a void function?

Define it as typedef VoidCallback = void Function(); or with parameters: typedef IntVoid = void Function(int value);.

Previous

dart extension methods

Next

dart callable classes

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.