Mixin

JS 不支持多继承,但可以通过 Mixin 模拟。

export function mix<T extends new (...args: any[]) => unknown>(ctor: T, ...bases: any[]) {
  bases.forEach((baseCtor) => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
      Object.defineProperty(
        ctor.prototype,
        name,
        Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null)
      )
    })
  })
  return ctor
}
class A {
  a() {}
}

class B {
  b() {}
}

class C {}
mix(C, A, B)

// class C extends mix(A, B) {}

interface C extends A, B {}

const c = new C()

console.log(c.a)

在线示例

参考链接: https://www.typescriptlang.org/docs/handbook/mixins.html#handbook-content

最后更新于