Interfaces vs. Type Aliases

1. Welcome and Icebreaker:

  • If you could choose between two ways to describe yourself, what would they be and why?

2. Outline the Session:

  • We’ll compare interfaces and type aliases in TypeScript: similarities, differences, and when to use each.
  • Learning Outcomes: Understand the strengths and limitations of both, and how to choose the right one for your use case.
  • Let’s compare and contrast!

3. Concept Explanation:

  • Interfaces and type aliases can both describe the shape of objects, but have some differences:
    • Interfaces can be extended and merged, and are best for object shapes and class contracts.
    • Type aliases are more flexible: they can represent primitives, unions, intersections, tuples, and more.
    • Interfaces support declaration merging; type aliases do not.
    • Use interfaces for public APIs and when you need to extend or implement; use type aliases for unions, intersections, and complex types.

4. Live Coding Demonstration:

// Interface
interface User {
  id: number;
  name: string;
}

// Type alias
type UserAlias = {
  id: number;
  name: string;
};

// Both can be used to type objects
const user1: User = { id: 1, name: "Alice" };
const user2: UserAlias = { id: 2, name: "Bob" };

// Extending
interface Admin extends User {
  role: string;
}
type AdminAlias = UserAlias & { role: string };

// Declaration merging (only works with interfaces)
interface User {
  email: string;
}
const user3: User = { id: 3, name: "Carol", email: "carol@example.com" };

// Type alias for union
type Status = "active" | "inactive";

// Interface for function type
interface Greeter {
  (name: string): string;
}
const greet: Greeter = name => `Hello, ${name}`;
console.log(greet("Dave"));

5. Tasks:

  • Short Exercise:
    1. Create an interface Animal and a type alias AnimalAlias with the same properties.
    2. Extend the interface and the type alias to add a species property.
    3. Demonstrate declaration merging with the interface (add a new property in a separate declaration).
    4. Create a union type alias for possible animal statuses (e.g., “wild”, “domestic”).