Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define angular's @Input decorator in an interface?

Given is the following Angular component:

export class NumberComponent implements NumberInterface {
  @Input() number;
  constructor() { }
}

Now I'm looking forward to implement the NumberInterface. That's what I've got so far:

export interface NumberInterface {
  number: number
}

Basically, I'm using the type Function to define the Decorator. Now I'm wondering if there is a more specific way to do this. The interface should force the component to implement angular's @Input decorator.

like image 782
Orlandster Avatar asked Apr 20 '18 18:04

Orlandster


1 Answers

Interfaces in Typescript strictly do not have value, as they are entities that only exist for type-checking and are not compiled into JS.

You can't define a decorator in an interface because the decorator has value. It's a function that takes an argument and gives value to the class property, and not a type.

Angular's @Input decorators themselves do have a typing, but it's impossible to type them in a lower-order class since that property is itself already a type, but given value by the decorator:

export interface ITest {

  prop: Input;
  prop2: InputDecorator;

}

export class Test implements ITest {

  @Input('thing') prop: string;
  @Input('thing2') prop2: string;

}

// typeerror: Test does not correctly implement ITest

However, component classes can be derived from in Angular, and the parent class' decorators will be inherited by the child. This is useful if you want to implement strong typing alongside a more polymorphic approach to your code:

export class NumberBase {

  @Input('number') number: number;

}

export class NumberComponent extends NumberBase {


  ngOnInit() {
    console.log(this.number); // works!
  }

}

Components can extend either plain TS classes or fully decorated Angular components.

like image 165
joh04667 Avatar answered Nov 03 '22 08:11

joh04667