看起来下面的代码没有编译:
interface IServiceBase {};
type INullableServiceBase = IServiceBase | undefined;
public GetService<T extends INullableServiceBase>(): T
{
return this._service;
}
这会产生 TS2322:无法将类型“INullableServiceBase”分配给类型“T”。类型“未定义”不能分配给类型“T”。
如何定义通用约束以允许可空类型?
最佳答案
问题是调用者是决定 T
的人。如果 this._service
定义为 IServiceBase | null
你有两个问题。
T
可能是IServiceBase
所以分配IServiceBase | null
不是类型安全的,因为this._service
可能为 nullT
可能是从IServiceBase
派生的类型(即IExtendedServiceBase
)。所以this._service
不会以任何方式满足T
。
这些理由足以让编译器拒绝这个。您可以强制使用类型断言 (this._service as T
),或者您可能会考虑根本不使用此泛型,因为调用者并不真正控制 T
:
function GetService(): INullableServiceBase
{
return this._service;
}
或者使服务类型的包含类通用:
class ServiceFactory<T extends INullableServiceBase> {
constructor(private _service: T) { }
public GetService(): T {
return this._service;
}
}
但是如果没有更多的上下文,很难说什么最有效。
关于TypeScript 泛型 "extends"约束 : Is there a nullable constraint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222047/