TypeScript: implements vs extends
In TypeScript's class-based object-oriented programming, implements and extends are two fundamental keywords that define relationships between classes and interfaces. They serve distinct purposes and are not interchangeable.
1. extends (Inheritance)
The extends keyword is used to create a subclass that inherits properties and methods from a single superclass. This is the classic "is-a" relationship.
- What it does: Inherits both the implementation (code in methods) and the shape (properties and method signatures).
- Usage: A class can
extendonly one other class.
class Animal {
move(distance: number = 0) {
console.log(`Animal moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark(); // Method from Dog
dog.move(10); // Method inherited from Animal
2. implements (Contracts)
The implements keyword is used to declare that a class will conform to the shape of one or more interfaces. It's a way to enforce a contract, ensuring the class has a specific set of properties and methods.
- What it does: Checks the class for the required shape but does not provide any implementation or inherit any code.
- Usage: A class can
implementmultiple interfaces.
interface Loggable {
log(message: string): void;
}
class ConsoleLogger implements Loggable {
// The class MUST provide an implementation for log()
log(message: string) {
console.log(message);
}
}
3. Summary of Differences
| Feature | extends |
implements |
|---|---|---|
| Purpose | Inheritance | Contract Enforcement |
| Target | Class extends Class | Class implements Interface |
| Number Allowed | One | Multiple |
| Inherits Code? | Yes | No |
| Inherits Shape? | Yes | Yes (checks against it) |
| Relationship | "is-a" (a Dog is an Animal) | "can-do" (a Logger can do logging) |
4. Combining extends and implements
A class can both extend a base class and implement multiple interfaces at the same time.
interface Serializable {
serialize(): string;
}
class Car extends Vehicle implements Serializable {
// Must implement serialize() from the Serializable interface
serialize(): string {
return JSON.stringify(this);
}
// Inherits methods like startEngine() from Vehicle
}
programming/javascript/typescript/typescript programming/javascript/typescript/abstract-classes