It would be great if we had type checking inside the SimpleChanges typescript parameter of ngOnChanges hook for the current Component.
This would prevent us from errors in the properties we check.
Using TypeScript 2.1 and the keyof functionality I have figured out the following type declarations (based on SimpleChanges) which seems to give us the necessary typed access to Component's properties:
export type ComponentChange<T, P extends keyof T> = {
previousValue: T[P];
currentValue: T[P];
firstChange: boolean;
};
export type ComponentChanges<T> = {
[P in keyof T]?: ComponentChange<T, P>;
};
Using those, declarations vscode editor automatically fetches the type info and auto completes the changes properties:
One problem though is that the changes parameter now will list each and every property of the component (and not only the @Input() properties) but I haven't figure out a better way than this.
I solve the issue using inheritance. First I create typed interface which extends SimpleChange class. You only need to do this once and import it in your components which need it.
interface TypedChange<T> extends SimpleChange
{
previousValue: T;
currentValue: T;
}
Second we extend the SimpleChanges interface with ones expected to change in our component. For example
interface MyComponentChanges extends SimpleChanges
{
RefreshQueue: TypedChange<number>
}
Lastly the implementation is
public ngOnChanges(changes: MyComponentChanges): void
{
if (changes.RefreshQueue)
{
if (!changes.RefreshQueue.isFirstChange())
{
if (changes.RefreshQueue.currentValue == 1)
{
DoSomething();
}
}
}
}
Intellisense screen shot below
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