On this page10 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Naming a Function Type
  4. 2. Naming Other Types
  5. 3. Just a New Name
  6. Code Examples
  7. Common Beginner Mistakes
  8. Practice Questions
  9. Practice Answers
  10. Key Takeaways

Lecture 049: typedef

DayExtra Topics
Lecture049 of 057
Estimated video length8 min
TargetDart 3.12
LevelBeginner

Some types are long and hard to read: int Function(int a, int b) or Map<String, dynamic>. A typedef gives a type a short, meaningful name, so your code explains itself.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 040 (higher-order functions) and 048 (anonymous functions).


Learning Objectives

  • Create a name for a function type with typedef
  • Use that name for variables and parameters
  • Create a short name for any other type
  • Know that a typedef is only a new name, not a new type

1. Naming a Function Type

A function that takes two ints and returns an int has the type int Function(int, int). Give it a name:

dart
typedef MathOperation = int Function(int a, int b);

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

int calculate(int x, int y, MathOperation op) => op(x, y);

void main() {
  print(calculate(6, 3, add));              // 9
  print(calculate(6, 3, multiply));         // 18
  print(calculate(6, 3, (a, b) => a - b));  // 3

  MathOperation op = multiply;
  print(op(4, 5));                          // 20
}

calculate(int x, int y, MathOperation op) is much easier to read than calculate(int x, int y, int Function(int, int) op).

typedef lines go at the top level of the file, outside main and outside classes.

2. Naming Other Types

A typedef works for any type, not only functions:

dart
typedef Json = Map<String, dynamic>;
typedef Scores = List<int>;

Json user = {'name': 'Ali', 'age': 20};
print(user['name']);   // Ali

Scores marks = [80, 92, 75];
print(marks.length);   // 3

3. Just a New Name

Scores is List<int>: same type, different name. Anything that works on a List<int> works on a Scores, and the two can be swapped freely. A typedef makes code easier to read; it doesn't add any new rules.


Code Examples

Example 1: Form Validation Rules

Each rule takes the text the user typed and returns an error message, or null if it's fine.

dart
typedef Validator = String? Function(String value);

String? notEmpty(String value) => value.trim().isEmpty ? 'Required' : null;
String? minLength8(String value) => value.length < 8 ? 'Must be at least 8 characters' : null;
String? hasDigit(String value) => value.contains(RegExp(r'[0-9]')) ? null : 'Must contain a number';

void check(String label, String value, List<Validator> rules) {
  for (var rule in rules) {
    var error = rule(value);
    if (error != null) {
      print('$label "$value": $error');
      return;
    }
  }
  print('$label "$value": OK');
}

void main() {
  var passwordRules = <Validator>[notEmpty, minLength8, hasDigit];
  check('Password', '', passwordRules);
  check('Password', 'abc', passwordRules);
  check('Password', 'abcdefgh', passwordRules);
  check('Password', 'abcdefg1', passwordRules);
}

Output

code
Password "": Required
Password "abc": Must be at least 8 characters
Password "abcdefgh": Must contain a number
Password "abcdefg1": OK

List<Validator> reads like plain English: a list of validators. Flutter's text fields use exactly this pattern for their validator: property.


Common Beginner Mistakes

1. Passing a function with the wrong shape

dart
typedef MathOperation = int Function(int a, int b);
String join(String a, String b) => a + b;

MathOperation op = join;
code
Error: A value of type 'String Function(String, String)' can't be assigned to a variable of type 'int Function(int, int)'.

The parameter and return types must match.

2. Writing a typedef inside main or a class: it must be at the top level of the file.

3. Expecting a new type: typedef Age = int; doesn't stop you passing any int where an Age is expected. For a truly separate type, write a class.


Practice Questions

  1. Write a typedef named Greeting for a function that takes a String and returns a String.
  2. With typedef Scores = List<int>;, is Scores s = [1, 2]; valid?
  3. Where in a file must a typedef go?
  4. Why use typedef at all?

Practice Answers

  1. typedef Greeting = String Function(String name);
  2. Yes. Scores is just another name for List<int>.
  3. At the top level, outside functions and classes.
  4. To give long or unclear types a short, meaningful name, which makes code easier to read.

Key Takeaways

  • typedef Name = SomeType; gives a type a new name.
  • Most useful for function types: typedef MathOperation = int Function(int a, int b);
  • Also handy for long types like Map<String, dynamic>.
  • It's only a name; the real type is unchanged.