2

In typescript, a class with static members is compiled into a function when each static member becomes a function object property.

For example:

class Config {
    static debug = true;
    static verbose = false;
}

Becomes

var Config = (function () {
    function Config() {
    }
    Config.debug = true;
    Config.verbose = false;
    return Config;
})();

Invoking JSON.stringify on such function object will result with undefined. What is the right way to stringify in that case?

2
  • 1
    What output are you expecting? JSON cannot represent functions. Are you wanting to treat the function as if it were an object literal containing just its static members? Commented Jul 3, 2015 at 9:59
  • @JamesAllardice exactly Commented Jul 3, 2015 at 10:46

1 Answer 1

3

Note that JSON.stringify does not take the functions. You could do it this way:

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.

An example:

Function.prototype.toJSON = Function.prototype.toJSON || function(){
    var props = {};
    for(var x in this){
        if(this.hasOwnProperty(x)) props[x] = this[x]
    }
    return props
}

var Config = (function () {
    function Config() {
    }
    Config.debug = true;
    Config.verbose = false;
    return Config;
})();

console.log(JSON.stringify(Config))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.