2017-02-23 44 views
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; } 
} 

因此,这是不符合承诺<>声明一个问题,它与泛型(我想)做。

在此先感谢!

回答

1

第一个例子在Typescript 2.2中可能会失败(可能是2.1),我认为这是由于带有Promises in Typescript。

第二个示例因为TypeScript处理与generics的类型兼容性而编译,特别是Simple<T>未使用type参数。

如果您做如下改变,你会得到预期的错误:

class Simple<T> { 
    ID: T; 
} 
+0

是的,你说得对!升级对第一个问题有帮助。谢谢你澄清第二条。一个真正的红色鲱鱼,我看到第二个问题的表现后,就驳回了承诺的潜在问题。 – Ben