📘

Interfaces: Defining Object Shapes

Beginner
90 XP
35 min
Lesson Content

Interfaces in TypeScript

Interfaces define the shape of objects. They're essential for React props, Vue components, and Angular services.

Basic Interface

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

const user: User = {
  name: "John",
  age: 30,
  email: "john@example.com"
};

Optional Properties

interface User {
  name: string;
  age?: number; // Optional
  email: string;
}

Readonly Properties

interface Point {
  readonly x: number;
  readonly y: number;
}

const point: Point = { x: 10, y: 20 };
// point.x = 5; // Error!

Interface Extensions

interface Animal {
  name: string;
}

interface Dog extends Animal {
  breed: string;
}

Interface for Functions

interface Calculator {
  (x: number, y: number): number;
}

const add: Calculator = (a, b) => a + b;
Example Code

Create and use interfaces to define object shapes

// Define an interface for a Book
interface Book {
  title: string;
  author: string;
  pages: number;
  isRead?: boolean;
}

// Create a book object
const myBook: Book = {
  title: "TypeScript Guide",
  author: "John Doe",
  pages: 300,
  isRead: true
};

console.log(`Book: ${myBook.title} by ${myBook.author}`);

Expected Output:

Book: TypeScript Guide by John Doe
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code