[英]Optional generic that extends interface
我有一个导出的抽象类,目前有一个泛型。 然而,我现在需要两个泛型。 我不想更改当前使用该类的所有删除类。 所以我想添加一个扩展接口的可选泛型类。
这是我目前拥有的
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'.
这是我卡住的地方,我怎样才能最好地解决这个问题?
如果我必须按照声明使用您的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>,
) { }
}
如果T1
是undefined
,那么Extract<T1, IBase>
将never
,并且T | never
T | never
只是T
......所以你想怎么工作。 如果T1
是某个联合(例如SomeSubtypeOfIBase | undefined
),则Extract<T1, IBase>
将仅包含可分配给IBase
的部分(例如SomeSubtypeOfIBase
)。
我不确定第二个参数T1
用途是什么,因此以下建议可能站不住脚,但是:您可能只想让T1
默认为never
并且不在T1
的域中包含undefined
。 执行此操作时,类型T | T1
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
的示例,我无法确定这是否会有所帮助。 但它要简单得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.