TypeScript 泛型 "extends"约束 : Is there a nullable constraint?

标签 typescript typescript-generics

看起来下面的代码没有编译:

interface IServiceBase {};
type INullableServiceBase = IServiceBase | undefined;

public GetService<T extends INullableServiceBase>(): T
{
  return this._service;
}

这会产生 TS2322:无法将类型“INullableServiceBase”分配给类型“T”。类型“未定义”不能分配给类型“T”。

如何定义通用约束以允许可空类型?

最佳答案

问题是调用者是决定 T 的人。如果 this._service 定义为 IServiceBase | null 你有两个问题。

  1. T 可能是 IServiceBase 所以分配 IServiceBase | null 不是类型安全的,因为 this._service 可能为 null
  2. T 可能是从 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/

相关文章:

typescript - typescript 中枚举的通用函数

typescript - 如何扩展 'Window' typescript 接口(interface)

typescript - ionic : How do I hide an element on load

TypeScript VS ScriptSharp——权衡是什么?

angularjs - 如何在枚举中使用 ng-if 条件? (angular2/ typescript )

Typescript:如何从返回函数的输入参数推断高阶函数中的泛型类型

typescript - 将函数返回值定义为读取对象中路径的类型

typescript - noImplicitAny 不适用于通用高阶函数

typescript - 推断函数返回类型,了解一个属性的值

javascript - typescript - 从日期中获取日期名称