简体   繁体   English

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

[英]Why field declaration is must in class as it implements an interface

I want to clear my concept in implementation of an interface on a class.我想清除我在类上实现接口的概念。

An interface is something like a template which cannot make an impact until a class implements it.接口就像一个模板,在类实现它之前不会产生影响。 (link) (关联)

So if I define an interface as:因此,如果我将接口定义为:

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

And then I make a class as:然后我做了一个类:

class Vehicle implements IVehicle {

}

It's giving me red underline at class name.它在班级名称上给了我红色下划线。 Why I must declare the fields again in the class as it is implementing an interface it must not fetch its fields?为什么我必须在类中再次声明字段,因为它正在实现一个不能获取其字段的接口?

Why we must write like this?为什么我们必须这样写?

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

Then what is the concept of interfaces that a class can't fetch the fields of an interface whose it implements, what if I don't implement an interface and directly declare the fields in a class.那么接口的概念是什么,一个类不能获取它实现的接口的字段,如果我不实现一个接口,直接在一个类中声明字段呢? I am thinking that why developers of TypeScript added this thing?我在想为什么 TypeScript 的开发人员添加了这个东西? It doubles up the code;它使代码翻倍; first make an interface, declare fields in there, than make a class (also add implements InterfaceName ) , then again declare those fields in that class, why?首先创建一个接口,在那里声明字段,然后创建一个类(还添加implements InterfaceName ,然后再次在该类中声明这些字段,为什么?

because this is also valid:因为这也是有效的:

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;
    }
}

An interface just says that an instance will have those fields, it doesn't say it must match that exact type.一个接口只是说一个实例将具有这些字段,它并没有说它必须匹配那个确切的类型。 The declaration you have in the class specifies that the implementation is to store an instance variable which needs to be initialized.您在类中的声明指定实现是存储需要初始化的实例变量。

You can narrow instance variables and widen method call signatures while still implementing an 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') {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM