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.
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.
Generic Typedefs
With Dart 2.13 and later, you can create generic typedefs. This is extremely powerful for creating reusable callbacks and transformers.
Using Typedefs as Callback Types
Typedefs shine when you have functions that accept callbacks. The alias documents what kind of callback is expected.
Typedef for Generic Collections
While less common, you can also alias regular types. This can simplify complex type names.
Typedefs with Named Parameters
You can define typedefs that include named parameters. This makes the callback more self‑documenting.
Best Practices
- Use meaningful names that describe the purpose (e.g.,
StringTransformer,ErrorCallback).
- Use meaningful names that describe the purpose (e.g.,
- Prefer generic typedefs over duplicating similar signatures.
- Use the new syntax (
=) for clarity and future‑proofing.
- Use the new syntax (
- Keep typedefs in a dedicated file if they are shared across many modules.
- Document the expected behavior of the function alias.
Key Takeaways
typedefcreates 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;.
- Use the modern syntax: