What is typedef?
A typedef creates an alias for a type — most commonly function types. It improves code readability by giving complex function signatures a meaningful name.
Function Type Aliases
// Without typedef:
void Function(String, int) callback;
List<Map<String, dynamic>> Function(String) queryFn;
// With typedef:
typedef Callback = void Function(String message, int code);
typedef QueryFn = List<Map<String, dynamic>> Function(String sql);
typedef Predicate<T> = bool Function(T value);
typedef Transformer<T, R> = R Function(T input);
// Usage:
void runWithCallback(Callback callback) {
callback('Success', 200);
}
void main() {
Callback myCallback = (msg, code) => print('[$code] $msg');
runWithCallback(myCallback); // [200] Success
}
Generic Typedef
typedef JSON = Map<String, dynamic>;
typedef JsonList = List<Map<String, dynamic>>;
typedef Mapper<T, R> = R Function(T);
typedef Comparator<T> = int Function(T a, T b);
// Use in a sortable list:
List<T> sortBy<T>(List<T> items, Comparator<T> compare) {
var sorted = [...items];
sorted.sort(compare);
return sorted;
}
void main() {
var numbers = [3, 1, 4, 1, 5, 9, 2, 6];
var sorted = sortBy(numbers, (a, b) => a.compareTo(b));
print(sorted); // [1, 1, 2, 3, 4, 5, 6, 9]
JSON user = {'name': 'Alice', 'age': 30};
print(user['name']); // Alice
}
Practical Example: Event System
typedef EventHandler<T> = void Function(T event);
typedef AsyncEventHandler<T> = Future<void> Function(T event);
class EventBus<T> {
final List<EventHandler<T>> _handlers = [];
void on(EventHandler<T> handler) => _handlers.add(handler);
void emit(T event) { for (var h in _handlers) h(event); }
}
void main() {
var bus = EventBus<String>();
bus.on((msg) => print('Handler 1: $msg'));
bus.on((msg) => print('Handler 2: $${msg.toUpperCase()}'));
bus.emit('hello');
}
Output:Handler 1: hello
Handler 2: HELLO
🧠 Quiz
1. What does typedef primarily create?
- A) A new class
- B) A type alias ✅
- C) An abstract interface
- D) A mixin
2. Can typedef be generic?
- A) No
- B) Yes ✅
- C) Only in Dart 3+
- D) Only for non-function types
Summary
typedef creates named type aliases, primarily for function signatures. Use typedef Name = ReturnType Function(ParamTypes). Generics work with typedef — typedef Mapper<T, R> = R Function(T). Typedef improves readability and is great for callback patterns and event systems.