Typescript Foundations / Class & Object Oriented Typescript

Implementing Interfaces in Class

When a class implements an interface:

  • ✅ It agrees to follow the contract (shape and behavior) described by the interface.

  • ❌ If it misses any properties or methods, TypeScript will throw an error.


✅ Basic Syntax

interface Greetable {
  name: string;
  greet(msg: string): void;
}

class Person implements Greetable {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet(msg: string): void {
    console.log(`${msg}, I’m ${this.name}`);
  }
}

const user = new Person("Codeveda");
user.greet("Hello"); // Output: Hello, I’m Codeveda

🧠 Key Rules

  • All required properties and methods in the interface must be defined in the class.

  • You can also add extra methods or properties in the class (TypeScript won’t complain).


✨ Optional & Readonly Interface Members

interface User {
  readonly id: number; //readonly
  username: string;
  email?: string; //optional
}

class Admin implements User {
  readonly id: number;
  username: string;
  email?: string;

  constructor(id: number, username: string, email?: string) {
    this.id = id;
    this.username = username;
    this.email = email;
  }
}

✅ If a property is marked readonly in the interface, it must be readonly in the class too.


🔁 Implementing Multiple Interfaces

interface Printable {
  print(): void;
}

interface Savable {
  save(): void;
}

class Report implements Printable, Savable {
  print() {
    console.log("Printing report...");
  }

  save() {
    console.log("Saving report...");
  }
}

🧱 Real-World Example: Button Component Interface


🚫 What You Can’t Do

  • You can’t implement a type alias directly if it’s not a pure object shape (e.g., union or tuple).

  • You must define all required members (no partial implementation allowed unless they're optional).


✅ Summary Table

Feature

Example

Implement one

class A implements B {}

Implement multiple

class A implements B, C {}

Must match types

✅ Required properties & methods

Optional supported

✅ property?: type

Readonly respected

✅ Must also be readonly in class