Skip to content

Instantly share code, notes, and snippets.

@ravindUwU
Created October 5, 2022 03:52
Show Gist options
  • Save ravindUwU/f27e5b2dbd3226d865baa7432f14d1f9 to your computer and use it in GitHub Desktop.
Save ravindUwU/f27e5b2dbd3226d865baa7432f14d1f9 to your computer and use it in GitHub Desktop.
import { OnChanges, SimpleChange, SimpleChanges } from '@angular/core';
/**
* {@link SimpleChange}, but with typed previous & current values.
*/
export type TypedChange<T> = Omit<SimpleChange, 'previousValue' | 'currentValue'> & {
previousValue: T;
currentValue: T;
firstChange: boolean;
};
/**
* {@link SimpleChanges}, but with members of the specified component type. IntelliSense will list
* all public members of the component; not just the inputs. Use {@link ngHasChange} to detect
* changes within this.
*/
export type TypedChanges<TComponent> = SimpleChanges & {
[member in keyof TComponent]?: TypedChange<TComponent[member]>;
};
/**
* {@link TypedChanges}, but with the specified members defined.
*/
export type TypedChangesWith<TComponent, TMember extends keyof TComponent> = TypedChanges<TComponent> &
Required<Pick<TypedChanges<TComponent>, TMember>>;
/**
* Returns whether the specified changes includes a change to the specified property of the component.
*/
export function ngHasChange<TComponent, TMember extends keyof TComponent>(
changes: TypedChanges<TComponent>,
member: TMember
): changes is TypedChangesWith<TComponent, TMember> {
return member in changes;
}
/**
* Implement this interface instead of {@link OnChanges} to receive {@link TypedChanges typed changes}
* instead of (untyped) {@link SimpleChanges}.
*/
export interface OnTypedChanges<TComponent> extends OnChanges {
ngOnChanges(changes: TypedChanges<TComponent>): void;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment