Monday, February 8, 2016

Tracing data member assignments with TypeScript


From time tot time, especially in a large codebase with lots of async operations, I have found myself wishing I could trace every assignment for a variable.

With TypeScript properties (Accessors), it is trivial to do just that.

Imagine that you want to trace "the "data" member:

class MyClass {
    public data: Number;
}


Simply comment out the existing member and replace it with a TypeScript property of the same name and type, and insert your trace code:

class MyClass {
    //public data: Number;
 
    public set data(value: Number) {
        console.log("MyClass::data - " + this._data + " -> " + value);
        console.trace();
        this._data = value;
    }
    public get data(): Number{
        return this._data;
    }
    private _data: Number;
}


This will resolve into some pretty innocuous JavaScript:

var MyClass = (function () {
    function MyClass() {
    }
    Object.defineProperty(MyClass.prototype, "data", {
        get: function () {
            return this._data;
        },
        //public data: Number;
        set: function (value) {
            console.log("MyClass::data - " + this._data + " -> " + value);
            console.trace();
            this._data = value;
        },
        enumerable: true,
        configurable: true
    });
    return MyClass;
})();

And now you will get a nice stack trace as well as from/to values for all your assignments.


browser compatibility notes: 
Object.defineProperty and console.trace are not available in older browsers.  Check the links for compatibility.

No comments:

Post a Comment