javascript - 为什么字段声明必须在类中,因为它实现了一个接口(interface)

标签 javascript typescript class implements

我想澄清我在类上实现接口(interface)的概念。

An interface is something like a template which cannot make an impact until a class implements it. (link)

所以如果我将接口(interface)定义为:

interface IVehicle {
    color: string,
    model_no: number,
}

然后我创建一个类:

class Vehicle implements IVehicle {

}

它在类名处给了我红色下划线。为什么我必须在类中再次声明字段,因为它正在实现一个不能获取其字段的接口(interface)?

为什么一定要这样写?

class Vehicle implements IVehicle {
    color: string;
    model_no: number;
}

那什么是接口(interface)的概念,一个类不能取到它实现的接口(interface)的字段,如果我不实现接口(interface)直接在类中声明字段怎么办。我在想为什么 TypeScript 的开发者要添加这个东西?它加倍了代码;首先创建一个接口(interface),在其中声明字段,而不是创建一个类(还添加implements InterfaceName),然后再次在该类中声明这些字段,为什么?

最佳答案

因为这也是有效的:

interface IVehicle {
    color: string;
    model_no: number;
}

class ClownCar implements IVehicle {
    // can be a subset of original type
    public color: 'red' | 'green' | 'blue';
    public model_no: 250 = 250;
}

class NonEditableCar implements IVehicle {
    // can use getter or setters instead, doesn't have to be normal field
    get color() {
        return 'grey';
    }
    get model_no(){
        return 100;
    }
}

一个接口(interface)只是说一个实例将有那些字段,它并没有说它必须匹配那个确切的类型。您在类中的声明指定实现是存储需要初始化的实例变量。

您可以在仍然实现接口(interface)的同时缩小实例变量并扩大方法调用签名:

interface VehicleCarrier {
    contents: IVehicle[];
    launch(count: number): void;
}

class AircraftCarrier implements VehicleCarrier {
    // this is more specific, and because the inteface forces you to write it you have to consider that
    // it should be more specific.
    public contents: (Plane | Submarine)[];
    // can extend call signatures for methods
    public launch(count: number, type: 'plane' | 'sub' = 'plane') {}
}

关于javascript - 为什么字段声明必须在类中,因为它实现了一个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878484/

相关文章:

javascript - jquery id选择改变类

typescript - 我可以声明模块在 Typescript 中全局可用吗?

c++ - 试图将两个类放在同一个命名空间的不同文件中,但只有第一个 #included 类有效

class - Yii2 在 afterLogin() 方法中包含函数?

python - 如何在 python 中使用另一个类的变量?

javascript - jsLint错误: “somefunction() was used before it was defined”

javascript - JavaScript 有集合数据结构的实现吗?

javascript - 让 AngularJS 在 json 中转义 & 符号

typescript - 如何防止 TypeScript 中断基于 Webpack 的 ProvidePlugin 上声明的未解析变量的 Webpack 构建?

typescript - 如何使 Visual Studio Code 停止显示 node_modules 文件夹的 typescript 错误?