Skip to content

Instantly share code, notes, and snippets.

@FabianLauer
Last active March 28, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FabianLauer/ec8e53494877e04d32ca2edbec2e02f6 to your computer and use it in GitHub Desktop.
Save FabianLauer/ec8e53494877e04d32ca2edbec2e02f6 to your computer and use it in GitHub Desktop.
TypeScript property change trace logs
/**
* Logs information whenever a decorated propery's value is changed.
* The log message will contain the previous value, the new value and a stack trace.
* @param message An optional message to write to the console when a change is detected.
* @example
* class Foo {
* @tracePropertyChanges('Foo bar')
* public bar: any;
* }
*
* const foo = new Foo();
* foo.bar = 123; // will log "CHANGE: Foo bar (bar) ..."
*/
export function tracePropertyChanges(message: string = '') {
return (target: any, key: string) => {
let value: any;
Object.defineProperty(target, key, {
get: () => value,
set: newValue => {
// tslint:disable:no-console
console.group(`CHANGE: ${message} (${key})`);
console.log('from', value, 'to', newValue);
console.trace();
console.groupEnd();
// tslint:enable:no-console
value = newValue;
}
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment