首页 > 解决方案 > 扩展接口的可选泛型

问题描述

我有一个导出的抽象类,目前有一个泛型。然而,我现在需要两个泛型。我不想更改当前使用此类的所有切除类。所以我想添加一个扩展接口的可选泛型类。

这是我目前拥有的

export abstract class SharedShell<T extends IBase, T1 extends IBase> implements OnInit, OnDestroy {}

使 T1 可选的最佳方法是什么?我尝试执行以下操作

export abstract class SharedShell<T extends IBase, T1 extends IBase | Undefined = Undefined> implements OnInit, OnDestroy {}

但是,这会导致类型错误。

'IBase' is assignable to the constraint of type 'T1', but 'T1' could be instantiated with a different subtype of constraint 'IBase'.

这就是我卡住的地方,我怎样才能最好地解决这个问题?

TS 游乐场示例

标签: angulartypescriptgenerics

解决方案


如果我必须使用你SharedShell声明的,那么我会使用像 Extract实用程序类型这样的条件类型来变成T1合适的东西:

export abstract class SharedShell<T extends IBase, T1 extends IBase | undefined = undefined> {
    constructor(private detailService: ISharedService<T | Extract<T1, IBase>>,
        private listService: ISharedService<T>,
    ) { }
}

If T1is undefined, then Extract<T1, IBase>will be never, and T | neveris just T... 这样就可以按照您的意愿工作。如果T1是某个联合(例如,SomeSubtypeOfIBase | undefined),那么Extract<T1, IBase>将仅包括它可分配给的部分IBase(例如,SomeSubtypeOfIBase)。


我不确定第二个参数的用途是什么T1,因此以下建议可能站不住脚,但是:您可能只想T1默认为never而不包含undefinedT1. 当你这样做时,类型T | T1总是可以分配的IBase,事情就会正常工作:

export abstract class SharedShell<T extends IBase, T1 extends IBase = never> {
    constructor(private detailService: ISharedService<T | T1>,
        private listService: ISharedService<T>,
    ) { }
}

同样,如果没有更多关于如何使用的示例T1,我无法确定这是否会有所帮助。但这要简单得多。


Playground 代码链接


推荐阅读