Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking for SimpleChanges interface in ngOnChanges hook

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.

like image 990
George Mavritsakis Avatar asked May 24 '17 14:05

George Mavritsakis


2 Answers

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:

enter image description here

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.

like image 114
George Mavritsakis Avatar answered Sep 23 '22 01:09

George Mavritsakis


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

enter image description here

like image 30
Ashg Avatar answered Sep 24 '22 01:09

Ashg