angular - 扩展接口的可选泛型
问题描述
我有一个导出的抽象类,目前有一个泛型。然而,我现在需要两个泛型。我不想更改当前使用此类的所有切除类。所以我想添加一个扩展接口的可选泛型类。
这是我目前拥有的
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>,
) { }
}
If T1
is undefined
, then Extract<T1, IBase>
will be never
, and T | never
is just T
... 这样就可以按照您的意愿工作。如果T1
是某个联合(例如,SomeSubtypeOfIBase | undefined
),那么Extract<T1, IBase>
将仅包括它可分配给的部分IBase
(例如,SomeSubtypeOfIBase
)。
我不确定第二个参数的用途是什么T1
,因此以下建议可能站不住脚,但是:您可能只想T1
默认为never
而不包含undefined
在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
,我无法确定这是否会有所帮助。但这要简单得多。
推荐阅读
- angular - 从订阅Angular 7的对象打印单个值
- asp.net-mvc - 将非托管 Oracle.DataAccess 驱动程序与 MVC5 和实体框架 6 一起使用
- excel - 如果它已经打开,我如何阻止powershell打开一个excel文件?
- javascript - 如何修复 node.js 上的 crypto.pbkdf2 错误
- php - Nginx 在启用 php 的位置内重写规则
- php - 读取 CSV 在不同的计算机上给出不同的输出
- javascript - 模式适用于 regex101 但不适用于 Google 脚本
- node.js - 如何将 Node.js 应用程序部署到远程服务器?
- python - 使用 gdata-python-client 和 OAuth2 令牌从 Google Contacts API 检索所有(其他)联系人?
- delphi - 将多个列表框值保存到单个文本文件中