Interfaces

An Interface defines a structural contract for object shapes, ensuring objects have required properties and correct data types.

1. Basic Interface Syntax

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

const userAccount: User = {
  id: 101,
  name: "Alice Johnson",
  email: "alice@example.com"
};

2. Optional (`?`) & Readonly Properties

interface Product {
  readonly id: number;   // Cannot be reassigned after creation
  name: string;
  price: number;
  description?: string;  // Optional property
}

const laptop: Product = {
  id: 5001,
  name: "MacBook Pro",
  price: 1999
  // description is optional!
};

// ❌ Error: Cannot assign to 'id' because it is a read-only property
// laptop.id = 5002;

3. Extending Interfaces (`extends`)

Interfaces can inherit properties from one or multiple parent interfaces:

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

interface Employee extends Person {
  employeeId: number;
  department: string;
}

const dev: Employee = {
  name: "Sarah",
  age: 28,
  employeeId: 404,
  department: "Engineering"
};

4. Index Signatures (Dynamic Keys)

Define type constraints for objects with unknown dynamic keys:

interface Dictionary {
  [key: string]: string;
}

const translations: Dictionary = {
  hello: "Hola",
  goodbye: "Adiós"
};

Next Up

Learn Type Aliases (`type`), Union (`|`), Intersection (`&`), and `type` vs `interface` comparison.

Next Lesson: Type Aliases vs Interfaces →