【问题标题】:How to do reflexive generic class in Typescript?如何在 Typescript 中做自反泛型类?
【发布时间】:2017-06-16 16:17:54
【问题描述】:

我正在尝试为量角器页面对象编写通用基类。它是一个自反泛型类,具有一个 init 方法,该方法在等待或不等待 angular 后返回自身,具体取决于对象是否为 Angular。我希望 init 方法返回正确的类型——扩展基类的类,但我收到一个编译错误,抱怨我无法返回“this”,因为它不是泛型参数的实例。

export abstract class AbstractLoadable<T extends AbstractLoadable<T>> {

    protected isAngularComponent: boolean;

    public constructor(isAngularComponent: boolean = true) {
        this.isAngularComponent = isAngularComponent;
    }

    public initComponent(): T {
        browser.waitForAngularEnabled(this.isAngularComponent);
        if(this.isAngularComponent) {
            browser.waitForAngular();
        }

        return this as T; // Error here.
    }
}

错误是:“this”类型无法转换为“T”类型。类型“AbstractLoadable&lt;T&gt;”与类型“T”不可比较。

这种模式适用于 Java,我是 JavaScript 和 typescript 的新手。是否可以在 Typescript 中实现这一点?

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    与 java 不同,typescript 有 polymorphic this type,这在这种情况下非常有用:

    export abstract class AbstractLoadable {
        protected isAngularComponent: boolean;
    
        public constructor(isAngularComponent: boolean = true) {
            this.isAngularComponent = isAngularComponent;
        }
    
        public initComponent(): this {
            browser.waitForAngularEnabled(this.isAngularComponent);
            if(this.isAngularComponent) {
                browser.waitForAngular();
            }
    
            return this;
        }
    }
    

    如您所见,它完全消除了这种情况下对泛型的需求。
    编译器知道正确的类并推断返回 this 是什么,所以假设你有:

    class MyClass extends AbstractLoadable { ... }
    

    然后:

    let instance = new MyClass().initComponent();
    

    将返回 MyClass 类型的值。

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2019-10-06
      • 2020-10-11
      • 2021-06-18
      • 2019-05-15
      • 1970-01-01
      • 2021-03-25
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多