Sub topic 16
Implementing Interfaces with Classes
Assume you know basic TypeScript types, functions, objects, and the this keyword. You should also understand that an interface describes the shape of an object.
An interface is a compile-time contract. A class uses implements to promise that it provides the interface's required public members.
Applying an interface
Consider an interface for anything that can calculate a payment:
interface Payable {
readonly employeeId: string;
calculatePay(): number;
}
class Contractor implements Payable {
constructor(
public readonly employeeId: string,
private hourlyRate: number,
private hours: number
) {}
calculatePay(): number {
return this.hourlyRate * this.hours;
}
}
function printPayment(item: Payable): void {
console.log(`${item.employeeId}: $${item.calculatePay()}`);
}
const contractor = new Contractor("c-42", 80, 10);
printPayment(contractor); // c-42: $800The implements Payable clause makes TypeScript check that Contractor has a public employeeId property and a public calculatePay method with the correct types. The class can have additional private members, such as hourlyRate and hours.
The interface does not create a parent class. It supplies no method implementation and does not exist in the JavaScript output. The class remains responsible for storing data and implementing behavior.
Visibility and common errors
Members required by an interface must be accessible from outside the class. Therefore, a class cannot satisfy a public interface method with a private or protected method.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
const logger = new ConsoleLogger();
logger.log("Saved");The parameter types and return type must also be compatible. A missing member, misspelled member, or incompatible type produces a compile-time error.
A class can implement multiple interfaces by separating them with commas:
interface Identifiable {
id: string;
}
interface Serializable {
serialize(): string;
}
class User implements Identifiable, Serializable {
constructor(public id: string, public name: string) {}
serialize(): string {
return JSON.stringify({ id: this.id, name: this.name });
}
}
const user = new User("u-1", "Mina");
console.log(user.serialize());This class must satisfy both contracts. Implementing interfaces is useful when unrelated classes need to work with the same function. It favors shared capabilities without forcing those classes into one inheritance hierarchy.
Exercise
What compile-time requirement does class Report implements Printable create?
Show answer
The class must provide every public member declared by Printable with compatible types.