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

30 天前
 ChrisFreeMan

我有两个抽象类,但是其结构是一样的,不同的是分别继承了不同的类,我要怎么简写这种情况。

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())
  }
}

868 次点击
所在节点    TypeScript
10 条回复
ChrisFreeMan
30 天前
没事...突然想起 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());
}
}
Opportunity
30 天前
你确定能这么写?
ChrisFreeMan
30 天前
@Opportunity 吃完饭回来试了下确实不能😅
Opportunity
30 天前
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) {
}
nagisaushio
30 天前
mixin
sapjax
30 天前
HTMLButtonElement 为什么不继承 HTMLElement ?
ChrisFreeMan
30 天前
@Opportunity 学到了👍长见识了。验证了可以通过编译。
ChrisFreeMan
30 天前
@sapjax 这是 web components 有一些情况子类需要调用元素自身的方法,这只是其中一个例子,比如还有 HTMLDialogElement, HTMLCanvasElement
echo0x000001
30 天前
这种情况要么再基于 HTMLElement 开发一个 themeWather 基类,两个子类继承这个基类。要么使用 mixin 实现多重继承,参考这个库 https://www.npmjs.com/package/ts-mixer
ChrisFreeMan
30 天前
@echo0x000001 暂时先不拆了,先不过度的设计,不然东西做不完。我的品味还没到那里就不强迫自己了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1032888

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX