Type Aliases
Intro to Type Aliases
Type aliases let you give names to types, making them reusable and your code
more readable.
// Without type alias - verbose and repetitive
const user1: { name: string; email: string; age: number } = { ... }
const user2: { name: string; email: string; age: number } = { ... }
// With type alias - clean and reusable
type User = { name: string; email: string; age: number }
const user1: User = { ... }
const user2: User = { ... }
When to Use Type Aliases
- Reusable types - When you use the same type multiple times
- Complex types - When inline types get unwieldy
- Self-documenting code - When a name adds clarity
- Union/intersection types - Type aliases are the only way to name these (we’ll cover unions in Exercise 02 and intersections in Exercise 04)
type ID = string | number
type Coordinates = [number, number]
type Handler = (event: Event) => void
Type Aliases in functions
You can use type aliases in function parameters and return types.
type Address = { street: string; city: string; state: string; zip: string }
type User = { name: string; email: string; age: number; address: Address }
function createUser({ address }: User): Address {
return address
}
Though, unless my type is reusable, I prefer to inline my type definition in functions parameters instead:
function LogInfo({ message, type }: { message: string; type: string }) {
console.log(`${type}: ${message}`)
}
Type Aliases Are Flexible
Type aliases work with any type, not just objects:
type StringOrNumber = string | number
type Point = [number, number]
type Callback = () => void
type UserID = string
Type aliases are one of the most commonly used TypeScript features. They're
the foundation for building a well-typed codebase.
In this exercise, you'll create and use type aliases.