使用TypeScript,如何强制实现类实现正确的函数规范?

时间:2017-05-12 17:56:00

标签: typescript interface

以下的TypeScript编译没有错误:

interface IPerson {
    name: string;
}
interface IVehicle {
    model?: string;
}
interface IClass {
    doSomething(person:IPerson): string;
}

class MyClass implements IClass {
    doSomething(car:IVehicle):string {
        return car.model;
    }
}

但我希望它引发错误,因为MyClass.doSomething接受了IVehicle,但它应该接受IPerson。如何让编译器强制该类的方法接受正确类型的参数?

2 个答案:

答案 0 :(得分:1)

我希望我能告诉你为什么这种情况正在发生,因为看起来这样的错误似乎很奇怪:

index.ts(11,14): error TS2420: Class 'MyClass' incorrectly implements interface 'IClass'.
  Types of property 'doSomething' are incompatible.
    Type '(car: IVehicle) => string' is not assignable to type '(person: IPerson) => string'.
      Types of parameters 'car' and 'person' are incompatible.
        Type 'IPerson' is not assignable to type 'IVehicle'.
          Property 'model' is missing in type 'IPerson'.

如果你转过身,你将收到我上面粘贴的错误:

interface IVehicle {
    model?: string;
}

成:

interface IVehicle {
    model: string;
}

但我和你在一起,无论IVehicle中的可选属性如何,我都会期待这个错误。希望有更熟悉编译器内部的人可以告诉我们原因。

答案 1 :(得分:0)

这是一个众所周知的问题:niba在评论中提到https://github.com/Microsoft/TypeScript/issues/7485