下面的 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
。如何让编译器强制类的方法接受正确类型的参数?
最佳答案
我希望我能告诉您为什么会发生这种情况,因为您没有收到如下所示的错误看起来确实很奇怪:
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
中的可选属性如何,我都希望出现该错误。希望更熟悉编译器内部的人可以告诉我们原因。
关于typescript - 使用 TypeScript,我如何强制类实现正确的函数规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43943847/