最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Typescript class instance to javascript object - Stack Overflow

programmeradmin2浏览0评论

This is my code:

class A{
    test: string
    constructor(test: string){
        this.test = test
    }
}
const a = new A("hi")
console.log(a)

This is my output:

A { test: 'hi' }

When I want to upload this as a Javascript object, it get's rejected because it ain't a Javascript object. I can make one by doing this:

const someJSON = JSON.stringify(a)
const javascriptObject = JSON.parse(someJSON)

But I think there must be a better way, this feels like a hack. How to convert a typescript class instance to a plain javascript object?

This is my code:

class A{
    test: string
    constructor(test: string){
        this.test = test
    }
}
const a = new A("hi")
console.log(a)

This is my output:

A { test: 'hi' }

When I want to upload this as a Javascript object, it get's rejected because it ain't a Javascript object. I can make one by doing this:

const someJSON = JSON.stringify(a)
const javascriptObject = JSON.parse(someJSON)

But I think there must be a better way, this feels like a hack. How to convert a typescript class instance to a plain javascript object?

Share Improve this question asked Mar 23, 2018 at 19:33 NoKeyNoKey 4131 gold badge16 silver badges45 bronze badges 11
  • 1 A typescript class instance is a javascript object. You see that on the console because that is the way Chrome outputs it: Type object. What exactly are you trying to achieve? – Oscar Paz Commented Mar 23, 2018 at 19:36
  • It isn't true. When I print typeof === 'object' on my instance, it is false. After the parse, it prints true – NoKey Commented Mar 23, 2018 at 19:37
  • It is true. If you do a instanceof Object it returns true. typeof "hello" outputs string, not object, and yet is a valid JavaScript object – Oscar Paz Commented Mar 23, 2018 at 19:39
  • 2 I want to upload this as a Javascript object, it get's rejected <= What exactly do you mean by "upload as a javascript object" and what do you mean by "rejected"? What does rejected mean? Is there an error message? If so please post it. – Igor Commented Mar 23, 2018 at 19:45
  • 1 Then this is a firebase specific issue. See also this "duplicate" github issue. In the future it helps to have context. Adding what you have above in your ment makes it much easier to understand by those reading through your question. – Igor Commented Mar 23, 2018 at 19:49
 |  Show 6 more ments

3 Answers 3

Reset to default 5

If you want a plain JS object instead of a class instance you can spread the properties for example:

class A{
    constructor(test){
        this.test = test
    }
}
const a = new A("hi");
const b = { ...a };

console.log('a:', a);
console.log('b:', b);
console.log('Is b instance of A:', b instanceof A);

You can use Object.setPrototypeOf() to set the prototype of your symbol explicitly to the default prototype of objects, which is Object.prototype:

class A {
    constructor(test) {
        this.test = test
    }
}

const a = new A("hi")
Object.setPrototypeOf(a, Object.prototype);
console.log({ a, proto: Object.getPrototypeOf(a) });

This will make a equal to { test: "hi" }.

You may need to add methods to your class in future, some properties may bee private. So add a method toObject. Then you will be able to use methods and provide data to api in needed format.

class A{
      constructor(private _test: string){

      }

      public toObject(){
        //return JSON.parse(JSON.stringify(this));
        //in case if you want to have underscored private
        let object = {};
        Object.keys(this).map((key: string) => {
          object[key.slice(1)] = this[key];
        });

        return object;
      }
    }

    const a = new A("hi")
    console.log(a);
    console.log('----------------------');
    console.log(a.toObject());
发布评论

评论列表(0)

  1. 暂无评论