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

标签 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。如何让编译器强制类的方法接受正确类型的参数?

最佳答案

我希望我能告诉您为什么会发生这种情况,因为您没有收到如下所示的错误看起来确实很奇怪:

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/

相关文章:

javascript - 如何将 html 字符串(html 标签)显示为文本区域中的内容?

java接口(interface)和新类

go - 为什么我们可以将结构体指针分配给接口(interface)变量,即使结构体指针没有实现接口(interface)?

java - 为什么不应该将两个集合接口(interface)一起实现?

java - 您可以同时使用 iText 在 Java 中查看和编辑 PDF 吗?

TypeScript:条件类型和使用 bool 参数来控制返回类型

typescript - 如何使用严格类型的有效负载发出事件? | Vue 3 Composition API + TypeScript

TypeScript 最简单的方法来检查项目是否存在于数组中,如 C# Linq Any(使用任何库)

c# 实现接口(interface)的抽象类

typescript - Atom typescript tsconfig 和 npm 配置