TypeScript Type Aliases
🏷️ TypeScript Type Aliases
They make your code cleaner, reusable, and easier to understand, especially for complex types.
1️⃣ Basic Type Alias
Instead of repeating a type again and again, define it once.
2️⃣ Type Alias for Object Types
Very common and very useful.
✅ Cleaner
✅ Reusable
✅ Readable
3️⃣ Optional & Readonly in Type Aliases
4️⃣ Type Alias with Union Types
Combine multiple possible types.
❌ Error:
5️⃣ Type Alias for Function Types
Define the function structure.
6️⃣ Type Alias for Arrays
7️⃣ Type Alias for Tuples
8️⃣ Type Alias with Intersection Types
Combine multiple types into one.
9️⃣ Type Alias vs Interface
| Feature | Type Alias | Interface |
|---|---|---|
| Object Types | ✅ Yes | ✅ Yes |
| Union Types | ✅ Yes | ❌ No |
| Intersection Types | ✅ Yes | ❌ No |
| Extend / Merge | ❌ No | ✅ Yes |
| Preferred for | Complex types | Object shapes |
📌 Rule of thumb:
-
Use type for unions, primitives, functions
-
Use interface for object structures (especially public APIs)
🔑 Type Aliases Summary
| Use Case | Example |
|---|---|
| Primitive | type ID = number |
| Object | type User = {} |
| Union | `type Status = “a” |
| Function | type Fn = () => void |
| Array | type List = string[] |
| Tuple | type T = [number, string] |
| Intersection | type A & B |
⭐ Best Practices
✔ Use type aliases to avoid repetition
✔ Use meaningful names
✔ Prefer type aliases for unions & functions
✔ Keep types small and composable
