我有两个抽象类,但是其结构是一样的,不同的是分别继承了不同的类,我要怎么简写这种情况。
export abstract class DivComponentsManager extends HTMLElement {
protected themeWatcher = themeWatcher
protected disposeFuncs: (() => void)[] = []
constructor() {
super()
}
abstract renderView(): Promise<void>
connectedCallback() {
this.renderView()
}
disconnectedCallback() {
this.disposeFuncs.forEach(func => func())
}
}
export abstract class ButtonComponentsManager extends HTMLButtonElement {
protected themeWatcher = themeWatcher
protected disposeFuncs: (() => void)[] = []
constructor() {
super()
}
abstract renderView(): Promise<void>
connectedCallback() {
this.renderView()
}
disconnectedCallback() {
this.disposeFuncs.forEach(func => func())
}
}
1
ChrisFreeMan OP 没事...突然想起 gpt3.5 免费了,直接问出了答案。
import { themeWatcher } from './themeWatcher'; // Import themeWatcher if not already imported export abstract class ComponentsManager<T extends HTMLElement | HTMLButtonElement> extends T { protected themeWatcher = themeWatcher; protected disposeFuncs: (() => void)[] = []; constructor() { super(); } abstract renderView(): Promise<void>; connectedCallback() { this.renderView(); } disconnectedCallback() { this.disposeFuncs.forEach(func => func()); } } |
2
Opportunity 219 天前
你确定能这么写?
|
3
ChrisFreeMan OP @Opportunity 吃完饭回来试了下确实不能😅
|
4
Opportunity 219 天前 1
function ComponentsManager<T extends (new (...args: any[]) => HTMLElement)>(base: T) {
abstract class ComponentsManager extends base { abstract renderView(): Promise<void>; connectedCallback() { this.renderView(); } } return ComponentsManager; } export abstract class DivComponentsManager extends ComponentsManager(HTMLDivElement) { } export abstract class ButtonComponentsManager extends ComponentsManager(HTMLButtonElement) { } |
5
nagisaushio 219 天前 via Android
mixin
|
6
sapjax 219 天前
HTMLButtonElement 为什么不继承 HTMLElement ?
|
7
ChrisFreeMan OP @Opportunity 学到了👍长见识了。验证了可以通过编译。
|
8
ChrisFreeMan OP @sapjax 这是 web components 有一些情况子类需要调用元素自身的方法,这只是其中一个例子,比如还有 HTMLDialogElement, HTMLCanvasElement
|
9
echo0x000001 219 天前
这种情况要么再基于 HTMLElement 开发一个 themeWather 基类,两个子类继承这个基类。要么使用 mixin 实现多重继承,参考这个库 https://www.npmjs.com/package/ts-mixer
|
10
ChrisFreeMan OP @echo0x000001 暂时先不拆了,先不过度的设计,不然东西做不完。我的品味还没到那里就不强迫自己了。
|