Type Aliases
By now the task tracker's types are getting long: "todo" | "doing" | "done" in five functions, the full task shape in three. Change a status and you must hunt down every copy. The fix is the keyword you have been quietly using all along: type.
The rule
typegives any type a name; the name is a nickname, not a new type.
A type alias names a type so you can refer to it:
type TaskId = number;
type Status = "todo" | "doing" | "done";
type Pair = [TaskId, string];
type Task = {
id: TaskId;
title: string;
status: Status;
};
type TaskFilter = (task: Task) => boolean;The right-hand side can be any type: a primitive, a union, a tuple, an object shape, a function type, or a combination. Aliases can refer to other aliases, which is how small names build up into a readable model. They can also take type parameters, like type Box<T> = { value: T }, a topic for a later course on generics.
The important subtlety: an alias does not create a separate type. It is just another name for the same thing.
type TaskId = number;
type UserId = number;
const t: TaskId = 5;
const u: UserId = t; // allowed: both are just numberTypeScript will not stop you mixing up a TaskId and a UserId, because both are number. The alias adds readability, not protection.
Two more facts:
- An alias cannot be declared twice with the same name in the same scope. (Interfaces behave differently here, as the last section shows.)
- Aliases are erased when compiled, like every type.
The shortcut
Whenever you type the same type expression twice, stop and ask "What would I call this?" Then name it once and use the name.
Spot the repeat
"todo" | "doing" | "done"appears in five parameter lists.
The trap is expecting two aliases of the same type to be kept apart. TaskId and UserId are interchangeable; if you need real separation, that takes a different technique.
Drills
Answer fast — trust the rule.
Which of these can a type alias name?
With type TaskId = number; type UserId = number;, what happens on const u: UserId = taskId;?
What happens if you write type Status = "todo"; twice in the same file?
Which alias describes a function that takes a Task and returns true or false?
Remember
typegives any type a name; the name is a nickname, not a new type.- Written the same type twice? Ask "what would I call this?" and name it.
- Trap: two aliases of the same type are interchangeable, so they do not prevent mix-ups.
