Type alias
- Dart course
- Intermediate
- Lesson 71/116
- 5 min
Learn Dart 3 type aliases.
Type aliases for complex types
In Dart 3 typedef works for any type, not only function types. This is called a type alias. For example typedef JsonMap = Map<String, dynamic>; expresses a long type with a short name.
Now you can write JsonMap data = {'name': 'Dart'};. The code becomes shorter and clearer. When the type changes you update only the alias.
A type alias is also documentation: the name UserId carries a meaning that a plain int does not.
Declaring a type alias
A type alias starts with the typedef keyword. Example: typedef UserId = int;. Now UserId can be used wherever int goes; they are fully equivalent.
Likewise typedef StringList = List<String>; gives the name StringList. You can write StringList names = ['Alex', 'Sam'];.
An alias only names; the compiler treats both names as the same type. So no conversion is needed between UserId and int.
Practice The UserId alias
Define typedef UserId = int;. Define typedef StringList = List<String>;. In main assign 42 to a UserId variable and put ['Alex', 'Sam'] into a StringList; print both on separate lines with print.
Starter code
// Define the UserId alias (int)
// Define the StringList alias (List<String>)
void main() {
// create a UserId and a StringList, print them
}Sample solution
typedef UserId = int;
typedef StringList = List<String>;
void main() {
UserId id = 42;
StringList names = ['Alex', 'Sam'];
print(id);
print(names);
}Expected output
42 [Alex, Sam]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What can a type alias shorten?
- A comment block
- A loop body
- A complex type like Map Correct answer
- An import statement
Explanation: a type alias shortens complex types like Map.
2 The StringList alias
typedef StringList = List____>;
typedef StringList = List<String>>;
Explanation: the generic parameter for List<String> is <String>.
3 Match the aliases
| Term | Meaning |
|---|---|
typedef UserId = int; |
Name: UserId |
typedef StringList = List<String>; |
Name: StringList |
typedef JsonMap = Map<String, dynamic>; |
Name: JsonMap |