简体   繁体   English

使用类或接口来输入打字稿组件

[英]Use Class or Interface to take input in typescript component

I want to create a component in angular 2 that will take some input parameters.I am little bit confused about what should I use class or interface for input and why??For the following component I have used interface 我想创建一个角度2的组件,该组件将使用一些输入参数。我对于应该使用类或接口以及为什么输入有点困惑,为什么?对于以下组件,我使用了接口

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  moduleId: module.id,
  selector: 'combo-compo',
  template: `
      <select name="theme" class="form-control" [ngModel]="selectedObject" (ngModelChange)="onChangeObj($event)">
        <option [ngValue]="theme" *ngFor="let theme of dataObject" >{{theme.value}}</option>
      </select>
            `
})

export class ComboComponent {
  selectedObject: ComboInterface;
  @Input() dataObject: Array<ComboInterface>;
  @Output() onComboChange = new EventEmitter();

  onChangeObj(newObj: ComboInterface) {
    this.selectedObject = newObj;
    this.onComboChange.emit(this.selectedObject);
  }

}

interface ComboInterface {
    key: string;
    value: string;
}

In Typescript, you are free to use either of CLASS or INTERFACE . 在Typescript中,您可以自由使用CLASSINTERFACE

Below are the reasons which can help you take the right decision in choosing the correct structure: 以下是可以帮助您正确选择正确结构的原因:

Interface : You can only declare your properties with its corresponding type. 接口 :您只能使用相应的类型声明属性。 This means you cannot have functions in it, nor those properties can be initialized at the time of declaration. 这意味着您不能包含函数,也不能在声明时初始化这些属性。

Class : You can declare your properties along with a default value and also with the functions. Class :您可以声明属性以及默认值和函数。

PS: Interfaces are preferred over classes when you just want the structure of the data PS:当您只需要数据的结构时,与类相比,接口是首选的

Interfaces are preferable to classes as they are more flexible, and any class could implement that interface and be used for the input. 接口比类更好,因为它们更灵活,并且任何类都可以实现该接口并用作输入。 Also, if you are unit testing you can create mock or stub classes that implement the interface so that you can test your components in isolation. 另外,如果您正在进行单元测试,则可以创建实现接口的模拟或存根类,以便可以独立测试组件。

Although, in practical terms, if you only ever have one class that implements this interface, and it isn't used anywhere else, then there probably isn't the need to go the extra step of creating an interface, and you should maybe just us a class. 尽管实际上,如果您只有一个实现该接口的类,并且在其他地方都没有使用过,那么可能就不需要执行额外的步骤来创建接口,您也许应该我们一堂课。

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

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