#is there any deserialize package or method to keep prototype?

3 messages · Page 1 of 1 (latest)

unborn jungleBOT
#
farad314#0

Preview:```ts
class Foo {
constructor(
private readonly bar: number,
) {}
getBar() {
return this.bar;
}
}
const foo = new Foo(42);
const deserializedFoo = JSON.parse(JSON.stringify(foo));

type typeOfFoo = typeof foo; // Foo
type typeOfDeserializedFoo = typeof deserializedFoo; // any
...```

keen drift
#

To do this you can make a parsing helper function that uses a JSON.parse() reviver. For example:

class Foo {
    constructor(private readonly bar: number) { this.bar = bar; }
    getBar() { return this.bar; }
}

function parseFoo(json: string): Foo {
    return JSON.parse(json, (key, value) => {
        if (value && typeof value === "object" && "bar" in value) {
            return Object.assign(new Foo(0), value);
        }
        return value;
    });
}

const foo = new Foo(42);
const deserializedFoo = parseFoo(JSON.stringify(foo));

type typeOfFoo = typeof foo; // Foo
type typeOfDeserializedFoo = typeof deserializedFoo; // Foo

You can test this with:

console.log(deserializedFoo instanceof Foo); // true
console.log(deserializedFoo.getBar()); // 42

Hope this helps :)

#

And also hope this does what you wanted it to do