Lesson 24 +10 XP

Class Interfaces (implements)

Class Interfaces (implements)

Classes can enforce structural compliance with one or more interfaces using the implements clause.

Implementing Interfaces

interface Printable {
  print(): void;
}

interface Serializable {
  serialize(): string;
}

class Invoice implements Printable, Serializable {
  constructor(public id: string, public amount: number) {}

  print(): void {
    console.log(`Invoice #${this.id}: ${this.amount}`);
  }

  serialize(): string {
    return JSON.stringify({ id: this.id, amount: this.amount });
  }
}

Interfaces vs Abstract Classes

FeatureInterfaceAbstract Class
JS Code OutputTranspiles to zero JS codeGenerates JS class output
Multiple InheritanceClasses can implement multiple interfacesClasses can inherit from only ONE base class
Implementation CodePure contracts (no method bodies)Can contain method implementations & state

TL;DR

  • Use implements to guarantee that a class conforms to interface specifications.
  • A class can implement multiple interfaces separated by commas.
  • Interfaces leave zero footprint in the compiled JavaScript output.