Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript class instance to 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?

like image 889
NoKey Avatar asked Nov 01 '25 07:11

NoKey


1 Answers

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);
like image 69
H.B. Avatar answered Nov 02 '25 22:11

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!