Aliasing Object Types
What you'll learn: How to use type aliases to give reusable names to object shapes, making your code cleaner and more maintainable.
The Problem: Repeating Complex Object Types
So far, you've seen object type literals defined directly where you need them. But what happens when you need the same object shape in multiple places? You'd have to copy-paste the entire structure:
function greetUser(user: { name: string; age: number }) {
console.log(`Hello, ${user.name}!`);
}
function updateUser(user: { name: string; age: number }) {
// update logic
}
This creates maintenance headaches. Change one property? Update it everywhere.
The Solution: Type Aliases for Objects
Just like you can alias primitives, you can alias object types to give them a reusable name:
type User = {
name: string;
age: number;
};
function greetUser(user: User) {
console.log(`Hello, ${user.name}!`);
}
function updateUser(user: User) {
// update logic
}
Now User is a clean, reusable name for that object shape. Change the definition once, and it updates everywhere.
Think of It as a Blueprint
A type alias for an object is like a blueprint for a building. Instead of describing "a structure with three bedrooms and two bathrooms" every time, you say "a Ranch-style home" — everyone knows what that means.
Key Takeaway: Use type AliasName = { properties } to name object shapes once and reuse them everywhere, keeping your code DRY (Don't Repeat Yourself) and easier to maintain.