Abstract class, implements và tính cấu trúc của class
Bài trước bạn đã thêm kiểu cho field và method. Bài này nói về thiết kế: làm sao để một nhóm class tuân theo cùng một "hợp đồng".
implements: class cam kết theo một interface
interface Notifier {
send(to: string, message: string): Promise<void>;
}
class EmailNotifier implements Notifier {
async send(to: string, message: string) {
console.log(`Email tới ${to}: ${message}`);
}
}
class SmsNotifier implements Notifier {
async send(to: string) { // ✅ ít tham số hơn vẫn hợp lệ
console.log(`SMS tới ${to}`);
}
}Nếu EmailNotifier thiếu send hoặc sai kiểu, lỗi báo ngay tại dòng class. Một class có thể implements nhiều interface: class A implements B, C {}.
WARNING
implements chỉ kiểm tra, không thay đổi kiểu của class. Tham số trong method vẫn phải tự ghi kiểu; nếu bỏ, chúng là any (và lỗi với noImplicitAny), dù interface đã khai báo.
abstract class: khung có sẵn một phần code
abstract class Report {
constructor(protected readonly title: string) {}
// method trừu tượng: class con BẮT BUỘC cài đặt
protected abstract rows(): string[];
// method cụ thể: dùng chung cho mọi class con
render(): string {
return [`# ${this.title}`, ...this.rows()].join("\n");
}
}
class SalesReport extends Report {
protected rows() {
return ["Tháng 1: 100tr", "Tháng 2: 120tr"];
}
}
new Report("x"); // ❌ Cannot create an instance of an abstract class
console.log(new SalesReport("Doanh thu").render());Đây là pattern Template Method: class cha định nghĩa quy trình (render), class con điền các bước (rows).
Interface hay abstract class?
interface | abstract class | |
|---|---|---|
| Có code dùng chung | ❌ | ✅ |
| Tồn tại lúc runtime | ❌ (bị xóa) | ✅ (là class thật) |
| Một class dùng nhiều cái | ✅ implements A, B | ❌ chỉ extends một |
Dùng với instanceof | ❌ | ✅ |
Quy tắc đơn giản: mặc định dùng interface; chỉ dùng abstract class khi thật sự có logic chung cần chia sẻ.
Class cũng là cấu trúc (structural)
TypeScript so sánh class theo hình dạng, không theo tên:
class Point { x = 0; y = 0; }
class Vector { x = 0; y = 0; }
const p: Point = new Vector(); // ✅ cùng hình dạng
const q: Point = { x: 1, y: 2 }; // ✅ object literal cũng đượcVì vậy implements không bắt buộc để class "tương thích" với interface — nó chỉ giúp báo lỗi sớm hơn và ở đúng chỗ.
Ngoại lệ: class có private/protected hoặc #private thì chỉ tương thích với chính nó (và class con):
class A { private secret = 1; }
class B { private secret = 1; }
const a: A = new B(); // ❌ Types have separate declarations of a private property 'secret'Dependency injection đơn giản
Kết hợp interface + constructor nhận phụ thuộc giúp code dễ test:
class OrderService {
constructor(private notifier: Notifier) {}
async place(email: string) {
await this.notifier.send(email, "Đặt hàng thành công");
}
}
// Trong test: truyền object giả, không cần class
const fake: Notifier = { send: async () => {} };
new OrderService(fake);TIP
Nhờ hệ kiểu cấu trúc, bạn hiếm khi cần thư viện mock: một object literal đúng hình dạng là đủ.
Comments