extends vs implements
extends - inheritance
A class inherits implementation (properties and methods) from a parent class.
ts
class Animal {
constructor(public name: string) {}
speak(): string {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak(): string {
return `${this.name} barks`;
}
}implements - contract
A class promises to satisfy a type shape - it must provide its own implementation.
ts
interface Serializable {
serialize(): string;
deserialize(data: string): void;
}
class User implements Serializable {
serialize(): string {
return JSON.stringify(this);
}
deserialize(data: string): void {
Object.assign(this, JSON.parse(data));
}
}Using both together
ts
class AdminUser extends User implements Serializable, Loggable {
// inherits from User, satisfies both interfaces
}Key difference
extends | implements | |
|---|---|---|
| Inherits implementation | Yes | No |
| Multiple | No (one class) | Yes (many interfaces) |
| Used with | A class (or an interface extending an interface) | Interfaces and object types |
implementswith an interface is a great way to enforce a contract across unrelated classes.
updated
did you know it?