Welcome back! I am Mihir, and in this lesson we will learn type aliases in TypeScript.
A type alias gives a name to a type so you can reuse it across your code.
Basic Type Alias
type Username = string;
let name: Username = "Mihir";Username is now another name for string.
This is useful when a basic type has business meaning.
Object Type Alias
The most common use is naming object shapes.
type User = {
id: number;
name: string;
email: string;
};
const user: User = {
id: 1,
name: "Mihir",
email: "mihir@example.com",
};Now you can use User anywhere you need this structure.
Optional Properties
type Product = {
id: number;
name: string;
description?: string;
};description is optional.
Valid:
const product: Product = {
id: 101,
name: "Keyboard",
};Readonly Properties
type Account = {
readonly id: number;
email: string;
};You can read id, but you cannot change it after creation.
const account: Account = {
id: 1,
email: "user@example.com",
};
account.email = "new@example.com";Invalid:
account.id = 2;Union Type Alias
Type aliases are excellent for unions.
type Status = "pending" | "success" | "failed";
let paymentStatus: Status = "pending";Invalid:
paymentStatus = "done";Only the listed values are allowed.
Function Type Alias
You can also name function shapes.
type CalculateTotal = (price: number, quantity: number) => number;
const calculateTotal: CalculateTotal = (price, quantity) => {
return price * quantity;
};This keeps callback-heavy code much cleaner.
Combining Types with Intersection
type HasId = {
id: number;
};
type HasTimestamps = {
createdAt: Date;
updatedAt: Date;
};
type DatabaseUser = HasId & HasTimestamps & {
name: string;
};DatabaseUser must have all properties from all combined types.
Type Alias Cannot Be Reopened
You cannot define the same type alias twice.
type User = {
name: string;
};
type User = {
email: string;
};This causes an error.
Interfaces behave differently, which we will learn next.
Quick Recap
- A type alias gives a reusable name to a type.
- Use
typefor objects, unions, literals, functions, and intersections. - Type aliases make code easier to read and maintain.
- A type alias cannot be reopened with another declaration of the same name.
Next up, we will learn Interfaces →, another powerful way to describe object shapes in TypeScript.