Skip to content

Interfaces

An interface is a contract that defines a set of methods that implementing classes must provide. It specifies what a class should do, but not how it should do it.

Interfaces enable abstraction and polymorphism without implementation details.


A USB port is an interface:

  • USB defines: “You must transfer data using this protocol”
  • Devices implement: Flash drives, keyboards, phones (all implement USB)
  • Benefit: Any USB device works with any USB port

AspectInterfaceAbstract Class
PurposeContract (what to do)Partial implementation (what + how)
MethodsAll abstract (traditionally)Mix of abstract and concrete
StateNo instance stateCan have fields/state
ConstructorsNoYes
Multiple inheritanceYes (implement many)No (extend one)

interface Loggable {
log(message: string): void;
}
class ConsoleLogger implements Loggable {
log(message: string): void {
console.log(`[LOG]: ${message}`);
}
}
class FileLogger implements Loggable {
constructor(private filename: string) {}
log(message: string): void {
console.log(`Writing to ${this.filename}: ${message}`);
}
}

  • Follow Interface Segregation — small, focused interfaces
  • Program to interfaces in your public API
  • Prefer interfaces over abstract classes for defining contracts

Previous Topic: Static Members → Next Topic: Abstract Classes →