What Is a Type Alias?
You'll learn how to create reusable names for types using TypeScript's type keyword.
The Core Idea
A type alias is simply a name you create for any type. Instead of writing the same complex type repeatedly throughout your code, you give it a descriptive name once and reuse that name wherever needed.
Think of it like creating a variable, but instead of storing a value, you're storing a type definition itself.
The type Keyword
You create type aliases using the type keyword followed by the name you want to use:
type Age = number;
type Username = string;
type IsActive = boolean;
Now Age, Username, and IsActive can be used anywhere you'd normally write number, string, or boolean.
Beyond Primitives
Type aliases really shine with more complex types:
type Point = {
x: number;
y: number;
};
type Callback = (result: string) => void;
type Status = "pending" | "complete";
Each of these aliases makes your code more readable and maintainable. When you see Point in a function parameter, you immediately understand what shape of object is expected.
Reusability in Action
type User = {
name: string;
age: number;
};
const user1: User = { name: "Alice", age: 30 };
const user2: User = { name: "Bob", age: 25 };
function greet(user: User): void {
console.log(`Hello, ${user.name}!`);
}
Without the User type alias, you'd repeat { name: string; age: number; } three times in this small example alone.
Key Takeaway: Type aliases use the type keyword to create named, reusable type definitions, making your code more readable and reducing repetition.