简体   繁体   中英

How to use an interface to ensure proper format of component input in Angular 2?

I've got an interface ( option.ts ):

export interface Option {
  label: string;
  model: any;
}

Which I then import into my component ( form-select.component.ts ):

import {Component, Input, Output, EventEmitter} from 'angular2/core';
import {Option} from './option';

@Component({
  selector: 'form-select',
  templateUrl: './app/assets/scripts/modules/form-controls/form-select/form-select.component.html',
  styleUrls: ['./app/assets/scripts/modules/form-controls/form-select/form-select.component.css'],
  inputs: [
    'options',
    'callback',
    'model',
    'label'
  ]
})

export class FormSelectComponent {
  @Input() model: any;
  @Output() modelChange: EventEmitter = new EventEmitter();

  isOpen: boolean = false;

  toggle() {
    this.isOpen = !this.isOpen;
  }

  close() {
    this.isOpen = false;
  }

  select(option, callback) {
    this.model = option.model;
    this.modelChange.next(this.model);

    callback ? callback() : false;
  }
}

Now I would like to use this interface to ensure that [options] that is passed to my select component from another component is correctly formatted and have the right types. [options] must be an array looking like this:

options = [
  {label: 'Hello world', model: 1},
  {label: 'Hello universe', model: 2},
  {label: 'Hello honey boo boo', model: 3}
]

Where each index object will use the Option interface, but how do I do this? I remember something along the lines of using Option[] in your component class but I'm not sure how to use [options] along with the interface and then passing it to the view (or however you're supposed to do it).

How can I achieve this?

You can do @Input() options:Option[] . But it will not have any effect at runtime as there is no runtime check for interfaces in javascript.
Check this question and this one and there are many others.

So, if you are only inputting like this:

<form-select [options]="options"></form-select>

You cannot ensure that the input options is implementing Option interface because the value is actually passed during runtime.

But, if you are assigning values to options like this:

this.options = someOptions;

Then, the IDE will show an error saying that someOptions is not of type Option[] . But this is at compile/development time only.

So, is there no point of typing the variable with an interface ?

I actually think it's good practice. At least, you make your code more readable. But, as far as ensuring the right interface is inputted into options , there is no point of using interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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