TypeScript Type Aliases
A type alias lets you give a name to any type, making complex types reusable and your code more readable. You create one with the `type` keyword followed by a name and an equals sign.
Type aliases can represent primitives, unions, tuples, or object shapes, and once defined, the alias name can be used anywhere that type is needed instead of repeating the full type definition.
type ID = string | number;
type User = { name: string; age: number };Creating a type alias
Writing `type ID = string | number;` creates a reusable name for that union. You can then use `ID` as a type anywhere in your code instead of repeating the union.
Object type aliases
Type aliases are frequently used for object shapes, such as `type User = { name: string; age: number };`, which documents exactly what properties a User object should have.
type ID = string | number;
function printId(id: ID) {
console.log(`ID: ${id}`);
}
printId(42);ID: 42ID is a reusable alias for the union type string | number.
type User = { name: string; age: number };
const u: User = { name: "Kim", age: 28 };
console.log(`${u.name} is ${u.age}`);Kim is 28The User type alias documents the exact shape an object must have.
Key points
- Type aliases are created with the `type` keyword.
- They can name unions, tuples, primitives, or object shapes.
- Aliases make complex types reusable and easier to read.
- Once defined, an alias can be used anywhere a type is expected.
