#typescript #beginner #interfaces

Day 5: Interfaces vs. Type Aliases

Defining Shapes

Welcome to Day 5! Yesterday we learned about type. Today we introduce its sibling: interface.

What is an Interface?

An interface is another way to name an object type.

interface UserInterface {
  name: string;
  age: number;
}

const user: UserInterface = {
  name: "Jack",
  age: 30
};

Interface vs. Type: Key Differences

For 90% of cases, they act the same. But here are the nuances:

1. Implementation

Interfaces are primarily designed to define the shape of objects that can be extended or implemented by classes (more on classes in Phase 2).

2. Declaration Merging (Interface only)

If you declare an interface twice, they merge. This is useful for extending third-party libraries.

interface Window {
  title: string;
}

interface Window {
  ts: TypeScriptAPI;
}

// The resulting Window interface has BOTH title and ts.

Types cannot do this.

3. Unions (Type only)

Interfaces cannot represent a union (e.g., this OR that). Types can.

type Status = "success" | "failure"; // Interface can't do this

Which One Should You Use?

  • Use interface when defining the shape of an object, especially if you’re writing a library or want object-oriented inheritance.
  • Use type for unions, primitives, tuples, or simple object shapes.

My Rule of Thumb: Start with type. If you need declaration merging or class implementation, switch to interface.

Challenge for Today

  1. Create a type for Car with make and model.
  2. Create an interface for Bicycle with brand and gearCount.
  3. Create objects for both.
  4. Try to “merge” the Bicycle interface by defining it again with a new property color and see if your object requires it.

See you on Day 6!