Mixin Constructor Type là gì?
Mixin Constructor Type là gì?
Trong TypeScript, mixin là hàm nhận vào một class và trả về một class mới kế thừa class đó kèm thêm tính năng. Mixin constructor type là kiểu mô tả "một constructor bất kỳ" để hàm mixin có thể nhận mọi class làm đầu vào.
// Kiểu constructor dùng cho mixin: bất kỳ class nào tạo ra object kiểu T
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date();
touch() { this.createdAt = new Date(); }
};
}
function Activatable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
isActive = false;
activate() { this.isActive = true; }
};
}
class User {
constructor(public name: string) {}
}
const SmartUser = Timestamped(Activatable(User));
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.