Typescript通用类参数

让·巴里尔

我目前正在为项目编程一些内部抽象类,我需要它是通用的(我希望它是可扩展的)。

我希望我的类被调用,因为它将像这样扩展T模板Sample extends T,以便具有的所有参数T例如,如果T是的Vue,我将有所有的Vue参数,如$el$options不重新声明的Vue也不包括它。

所以我有以下内容:

export namespace SDK {

  export abstract class Sample<T> {

    private static methods: any = {
      hello: Sample.prototype.hello
    }

    abstract callMe () : void;

    x: number = 0
    y: number = 0
    width: number = 1
    height: number = 1

    hello (): void {
      console.log('Sample hello world')
      this.callMe()
    }
  }
}

但是我不知道如何处理将T的属性包含到Sample中。

我希望它像:

export namespace SDK {

  export abstract class Sample<T> {

    private static methods: any = {
      hello: Sample.prototype.hello
    }

    abstract callMe () : void;

    x: number = 0
    y: number = 0
    width: number = 1
    height: number = 1

    // T properties (Vue example)
    $el: HTMLElement
    ...

    hello (): void {
      console.log('Sample hello world')
      this.callMe()
    }
  }
}

我希望我的班级被称为:

export default class MyComponent extends SDK.Sample<Vue> {
  name: string = 'my-component';

  callMe () : void {
    console.log('called')
  }

  mounted () : void {
    this.hello()
  }
}

我没有发现任何有关允许从模板化类中进行扩展的内容。

贾卡尔兹

我认为@TitianCernicovaDragomir使用mixins基本上正确。我有类似的代码,出于完整性考虑,我将发布这些代码,因为我认为我们采用的方法略有不同,并且它们的优缺点也有所不同。

以下代码确实强制您实现abstract方法,并允许您访问静态成员。但是您通过使用私有的未导出名称来支付费用,这最终使您无法将其设置为供他人使用的库。我认为有解决方法,但我不想对此事走得太远。

无论如何,这里是Sample

export namespace SDK {

  export type Constructor<T> = {
    new(...args: any[]): T;
    readonly prototype: T;
  }

  export function Sample<C extends Constructor<{}>>(ctor: C) {
    abstract class Sample extends ctor {
      private static methods: any = {
        hello: Sample.prototype.hello
      }
      abstract callMe(): void;
      x: number = 0
      y: number = 0
      width: number = 1
      height: number = 1

      hello(): void {
        console.log('Sample hello world')
        this.callMe()
      }

    }
    return Sample;
  }

}

及其用法:

export default class MyComponent extends SDK.Sample(Vue) {
  name: string = 'my-component';

  callMe () : void {
    console.log('called')
  }

  mounted () : void {
    this.hello()
  }
}

祝好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章