Interfaces vs. Types: Defining Shapes

Interfaces vs. Types: Defining Shapes in JavaScript: In TypeScript, you need a way to describe what your objects look like.

Concept Explanation

In TypeScript, you need a way to describe what your objects look like. You have two main tools: Interfaces and Types.

  • Interface: Think of this as a "Contract" for an object. "Every User MUST have an ID and a Name."
  • Type Alias: Think of this as a "NickName" for a specific set of rules.

Syntax or Core Structure

Interface (Extendable)

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

interface Admin extends User {
  role: 'super' | 'editor';
}

Type Alias (Flexible)

type Status = "pending" | "success" | "error";
type ID = string | number;

const myId: ID = 42;
const myStatus: Status = "success";

Which Should I Use?

The rule of thumb most teams follow: use interface for object shapes, type for everything else.

  • interface can be reopened — declare it twice and TypeScript merges them (handy for extending library types).
  • type can express things interfaces can't: unions (A | B), tuples ([number, string]), and mapped types.
  • Both compose: interfaces use extends; types use the & intersection operator.

Common Mistakes

  • Union in an Interface: You can't write interface X = A | B. Unions need a type.
  • Accidental Merging: Declaring the same type twice is an error; declaring the same interface twice silently merges them — surprising if you didn't mean it.
  • Overusing Optional: Marking everything ? optional defeats the safety. Only mark what's truly optional.

Best Practices

  • Be Consistent: Pick one style per project so the codebase reads uniformly.
  • Model the Domain: Name shapes after real concepts (Order, Invoice) rather than generic Data1.
  • Prefer Unions for State: type Status = "loading" | "done" makes invalid states impossible to represent.

Practice Exercises

  1. The Contract: Create an interface Product with a name, price, and an optional description.
  2. The Extender: Create an interface ElectronicProduct that extends Product and adds a voltage property.
  3. The Union: Create a type PaymentMethod that can only be "CreditCard", "PayPal", or "Bitcoin".