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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With