【问题标题】:TypeScript: Equivalent of C#'s Generic Type Constraint for extending class?TypeScript:相当于 C# 的用于扩展类的通用类型约束?
【发布时间】:2019-01-01 13:44:51
【问题描述】:

我正在尝试编写一个受保护的抽象类,它可以将子类类型作为超类构造函数的方法签名中的类型参数。

我正在寻找类似于 C# 的通用类型约束(where 关键字),以便我可以在参数列表中使用子类型。

//                    where T : <base class name>
BaseAuthController<T> where T : BaseAuthController

当前超类

export abstract class BaseAuthController {
    protected constructor(
        protected dialogRef:
            //This class shouldn't know about child classes
            MatDialogRef<Child1DialogComponent> |
            MatDialogRef<Child2DialogComponent> |
            MatDialogRef<Child3DialogComponent>
    ) {

    }
}

当前子类

export class Child1DialogComponent extends BaseAuthController {
    constructor(dialogRef: MatDialogRef<Child1DialogComponent>) {
        super(dialogRef);
    }
}

理想的超类

export abstract class BaseAuthController<T> {
    protected constructor(protected dialogRef: MatDialogRef<T>) {

    }
}

参考文献

【问题讨论】:

    标签: c# angular typescript generics typescript-generics


    【解决方案1】:

    当然,它在操作上是完全不同的,但有一种方法可以达到相同的结果:

    export abstract class BaseAuthController<T extends SubClass> {
        protected constructor(protected dialogRef: MatDialogRef<T>) {
    
        }
    }
    

    结合统一类型意味着我们可以指定多个孩子:

    export abstract class BaseAuthController<T extends SubClass1 | SubClass2> {
        protected constructor(protected dialogRef: MatDialogRef<T>) {
    
        }
    }
    

    【讨论】:

    • 感谢您的回复,但我认为这并不能解决我试图摆脱的根本问题,即父类必须了解每个子类
    【解决方案2】:

    我认为您可能想要自界泛型:

    export abstract class BaseAuthController<T extends BaseAuthController<T>> {
      protected constructor(protected dialogRef: MatDialogRef<T>) {}
    }
    

    这种行为通常在 TypeScript 中使用polymorphic this types 完成,但您不能在构造函数中引用this 类型。有一个open issue about this,但看起来不会很快解决。幸运的是,您仍然可以do it the way Java does。你的子类应该可以正常工作:

    export class Child1DialogComponent extends BaseAuthController<Child1DialogComponent> {
      constructor(dialogRef: MatDialogRef<Child1DialogComponent>) {
        super(dialogRef);
      }
    }
    

    希望有所帮助;祝你好运!

    【讨论】:

    • 我目前正在尝试这种方法。这看起来很有希望。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 2020-05-27
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多