想请教个 TypeScript 抽象类继承父类的问题。

查看 88|回复 8
作者:ChrisFreeMan   
我有两个抽象类,但是其结构是一样的,不同的是分别继承了不同的类,我要怎么简写这种情况。
export abstract class DivComponentsManager extends HTMLElement {
  protected themeWatcher = themeWatcher
  protected disposeFuncs: (() => void)[] = []
  constructor() {
    super()
  }
  abstract renderView(): Promise
  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
  connectedCallback() {
    this.renderView()
  }
  disconnectedCallback() {
    this.disposeFuncs.forEach(func => func())
  }
}
ChrisFreeMan
OP
  
没事...突然想起 gpt3.5 免费了,直接问出了答案。
import { themeWatcher } from './themeWatcher'; // Import themeWatcher if not already imported
export abstract class ComponentsManager extends T {
protected themeWatcher = themeWatcher;
protected disposeFuncs: (() => void)[] = [];
constructor() {
super();
}
abstract renderView(): Promise;
connectedCallback() {
this.renderView();
}
disconnectedCallback() {
this.disposeFuncs.forEach(func => func());
}
}
Opportunity   
你确定能这么写?
ChrisFreeMan
OP
  
@Opportunity 吃完饭回来试了下确实不能😅
Opportunity   
function ComponentsManager HTMLElement)>(base: T) {
abstract class ComponentsManager extends base {
abstract renderView(): Promise;
connectedCallback() {
this.renderView();
}
}
return ComponentsManager;
}
export abstract class DivComponentsManager extends ComponentsManager(HTMLDivElement) {
}
export abstract class ButtonComponentsManager extends ComponentsManager(HTMLButtonElement) {
}
nagisaushio   
mixin
sapjax   
HTMLButtonElement 为什么不继承 HTMLElement ?
ChrisFreeMan
OP
  
@Opportunity 学到了👍长见识了。验证了可以通过编译。
ChrisFreeMan
OP
  
@sapjax 这是 web components 有一些情况子类需要调用元素自身的方法,这只是其中一个例子,比如还有 HTMLDialogElement, HTMLCanvasElement
您需要登录后才可以回帖 登录 | 立即注册

返回顶部