Object Types and InterfacesLesson 2.3
How to extend and implement interfaces in TypeScript
extends keyword for interfaces, multiple inheritance, implements keyword, class interface contracts, interface composition
Extending interfaces
Use extends to build on an existing interface without modifying it:
interface Shape {
color: string;
}
interface Circle extends Shape {
radius: number;
}
const c: Circle = { color: "red", radius: 10 };Interfaces can extend multiple parents:
interface Serializable { serialize(): string; }
interface Loggable { log(): void; }
interface Entity extends Serializable, Loggable {
id: number;
}implements — enforcing contracts on classes
A class can declare that it satisfies an interface with implements:
interface Printable {
print(): void;
}
class Invoice implements Printable {
print() {
console.log("Printing invoice...");
}
}
// Missing print() method would be a compile errorimplements only checks that the class has the required shape. It does not inherit any implementation. Use it to document and enforce contracts between modules, especially when multiple classes should behave the same way from the outside.
