【发布时间】: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