Type aliases
| The type keyword | |
| Compose aliases | |
| Alias vs interface preview | |
| Naming with Type suffix |
The type keyword
A type alias gives a reusable name to any type. Define it once with the type keyword, then use the name everywhere instead of repeating the full spelling:
type UserId = string;
const id: UserId = "u-42";
console.log(id);
u-42
UserId reads as one clear idea across the codebase. When the underlying type changes later, a single alias edit updates every usage at once.
Compose aliases
Aliases combine into larger shapes. Small names slot into object fields, so complex types grow from simple named parts:
type UserId = string;
type User = {
id: UserId;
name: string;
};
const tom: User = { id: "u-1", name: "Tom" };
console.log(tom.name);
Tom
The User alias reuses UserId for its id field. Building types from named blocks keeps each definition short and easy to review.
Alias vs interface preview
Interfaces describe object shapes too, and the next lesson covers them in full. For now, notice that both spellings below accept the same objects:
interface Admin {
id: string;
level: number;
}
const boss: Admin = { id: "a-1", level: 5 };
console.log(boss.level);
5
As a rule of thumb, either form fits plain object shapes. Aliases additionally cover unions and single primitives, which the coming lessons explore.
Naming with Type suffix
A Type suffix marks a name as type level, apart from values that exist at run time. Readers spot the role at once, even in long files:
type StatusType = "on" | "off";
const status: StatusType = "on";
console.log(status);
on
StatusType can only ever be one of two texts, so typos fail the compile. Adopt the suffix across the project and every type name tells its own story.
Next: Interfaces
Article author: Arthur Isaev