Interfaces

Interfaces describe the shape of objects and serve as contracts for classes.

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

// Object literal adhering to the User interface
const user: User = { name: "Hayes", id: 0 };

// A more complex interface with a method
interface Person {
  name: string;
  age: number;
  greet(): string;
}

const person: Person = {
  name: "Merrick",
  age: 22,
  greet() {
    return `Hello, I'm ${this.name}`;
  }
};

console.log(person.greet()); // Output: Hello, I'm Merrick

Implementing an interface in a class:

class UserAccount implements User {
  constructor(public name: string, public id: number) {}
}

const user2: User = new UserAccount("Murphy", 1);
console.log(user2);

Type Aliases

Type aliases let you name any type (primitive, union, or object).

type Score = number;

type Player = {
  name: string;
  score: Score;
};

const player: Player = { name: "Alex", score: 100 };

Interface vs. Type Alias Comparison

Feature interface type (Type Alias)
Purpose Define object shapes & class contracts Create aliases for any type
Usage Best for objects and classes Flexible: objects, primitives, unions, functions, etc.
Extending Uses extends to inherit from another interface Uses & (intersection) to combine types
Merging Can merge declarations (same name interfaces merge) Cannot merge (redeclaring a type with the same name causes error)
Computed Properties Supported Not supported
Performance Slightly slower but more robust Generally faster compilation