angularvisual-studio-codelifecycletypescript2.1ngonchanges

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.


Solution

  • 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.