Web Analytics

Type Aliases

Beginner~15 min

Type aliases create custom names for any type, making code more readable and maintainable.

Basic Type Alias

Use the type keyword to create reusable type definitions:

Output
Click Run to execute your code
Naming Convention: Use PascalCase for type aliases (e.g., UserId, Point).

Union Types

Type aliases are perfect for union types (OR logic):

type Status = "pending" | "approved" | "rejected";
type ID = string | number;

let orderStatus: Status = "pending";
let userId: ID = "user123";
let productId: ID = 456;

When to Use Type Aliases

  • Union types: string | number
  • Primitive aliases: type ID = string
  • Tuple types: type Point = [number, number]
  • Function types: type Handler = (e: Event) => void
  • Complex types: Combinations of the above

Type Alias vs Interface

Use Case Recommendation Example
Object shape Interface interface User { }
Union type Type alias type ID = string | number
Primitive alias Type alias type Email = string
Tuple Type alias type Point = [number, number]
Function type Either type Fn = () => void

Common Patterns

1. String Literal Unions

type Direction = "north" | "south" | "east" | "west";
type Theme = "light" | "dark" | "auto";

2. Intersection Types (AND logic)

type Timestamped = { createdAt: Date };
type User = { userName: string };
type TimestampedUser = User & Timestamped;

3. Utility Type Aliases

type Nullable = T | null;
type Optional = T | undefined;

Common Mistakes

1. Redeclaring Type Aliases

// ✗ Wrong - cannot redeclare
type ID = string;
type ID = number;  // Error!

// ✓ Correct - use union
type ID = string | number;

2. Confusing Type Alias with Value

type Point = { x: number; y: number };

// ✗ Wrong - Point is a type, not a value
let p = new Point();

// ✓ Correct
let p: Point = { x: 10, y: 20 };

Summary

  • Use type keyword to create aliases
  • Perfect for unions, primitives, tuples
  • Cannot be redeclared (unlike interfaces)
  • Use PascalCase naming convention

What's Next?

Next: Extending Interfaces to build complex types!