【问题标题】:Typescript does not enforce typing when returning a generic from an abstract function从抽象函数返回泛型时,Typescript 不强制键入
【发布时间】:2017-02-23 03:06:42
【问题描述】:

我正在使用 Visual Studio 2015 和 Typescript 2.0.3.0。

我有一个非常简单的继承模型,其中我的基类有一个返回 Promise 的抽象方法。

如您所见,基类使用泛型来限制子类使用的模型类型,在本例中为 TModel。

当我声明一个返回 TModel 的抽象方法 GetVehicle 时,Typescript 将强制我的子类 (GrandPrix) 返回类型“Car” - 这很棒。

但是,如果我将返回类型更改为 Promise,Typescript 将不再强制执行返回类型:

interface IVehicle {
    Name:string;
}

class Car implements IVehicle {
    Name: "CAR";
}

class MotorBike implements IVehicle {
    Name: "MotorBike";
}


abstract class Race<TModel extends IVehicle> {

    protected abstract GetVehiclePromise(): Promise<TModel>;
    protected abstract GetVehicle(): TModel;
}

class GrandPix extends Race<Car> {
    // This works - it has to be type 'Car'
    protected GetVehicle(): Car { return null; }

    // This works, but SHOULD NOT - I can return Promise<anything_at_all> and it still compiles. Even something non-IVehicle like Promise<string>
    protected GetVehiclePromise(): Promise<MotorBike> { return null; }
}

有趣的是,我还尝试将 Promise 的使用替换为另一个接受泛型的类 - 同样的问题:

class Simple<T> {
    ID: "";
}

abstract class Race<TModel extends IVehicle> {
    protected abstract GetVehiclePromise(): Simple<TModel>;
}

class GrandPix extends Race<Car> {
    // Also compiles when it should not
    protected GetVehiclePromise(): Simple<MotorBike> { return null; }
}

所以这不是 Promise 声明的问题,它与泛型有关(我认为)。

提前致谢!

【问题讨论】:

    标签: generics typescript abstract


    【解决方案1】:

    第一个示例将在 Typescript 2.2(可能也是 2.1)中按预期失败,我相信这是由于 issue with Promises in Typescript。

    第二个示例编译是因为 TypeScript 如何处理与 generics 的类型兼容性,特别是 Simple&lt;T&gt; 不使用类型参数。

    如果您进行以下更改,您将收到预期的错误:

    class Simple<T> {
        ID: T;
    }
    

    【讨论】:

    • 是的,你是对的!升级帮助解决了第一个问题。谢谢你对第二个问题的澄清。一个真正的红鲱鱼,一旦我看到第二个问题出现,我就用承诺驳回了一个潜在的问题。
    猜你喜欢
    • 2019-01-07
    • 2018-10-22
    • 1970-01-01
    • 2020-06-09
    • 2021-05-28
    • 2021-02-05
    • 2019-07-19
    • 2022-12-21
    • 2021-10-06
    相关资源
    最近更新 更多