1
我正在使用Visual Studio 2015和Typescript 2.0.3.0。从抽象函数返回泛型时,Typescript不强制执行打字
我有一个非常简单的继承模型,其中我的基类有一个抽象方法返回一个Promise。
如您所见,基类使用泛型来限制子类使用的模型的类型,在本例中为TModel。
当我声明一个返回TModel的抽象方法GetVehicle时,Typescript将强制我的子类(GrandPrix)返回类型“Car” - 这太棒了。
但是,如果我改变返回类型的诺言,打字稿将不再强制执行的返回类型:
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; }
}
有趣的是,我自己也尝试与接受通用的另一个类替换使用无极 - 同样的问题:
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; }
}
因此,这是不符合承诺<>声明一个问题,它与泛型(我想)做。
在此先感谢!
是的,你说得对!升级对第一个问题有帮助。谢谢你澄清第二条。一个真正的红色鲱鱼,我看到第二个问题的表现后,就驳回了承诺的潜在问题。 – Ben