Loading lessons...
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
| Feature | Interface | Abstract Class |
|---|---|---|
| JS Code Output | Transpiles to zero JS code | Generates JS class output |
| Multiple Inheritance | Classes can implement multiple interfaces | Classes can inherit from only ONE base class |
| Implementation Code | Pure contracts (no method bodies) | Can contain method implementations & state |
TL;DR
- Use
implementsto 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.