Skip to content

Custom classes will crash if using accessors because created with Object.create instead of new Class #331

@pie6k

Description

@pie6k

Currently, when registering custom class with registerClass, and then deserializing, new instance of the class is created with:

(

return Object.assign(Object.create(clazz.prototype), v);
)

It leads tonon-trivial issues, eg code below will crash with error:

TypeError: Cannot write private member #bar_accessor_storage to an object whose class did not declare i

Crashing code:

const superjson = new SuperJSON();

class Foo {
  accessor bar!: string; // https://github.com/tc39/proposal-grouped-and-auto-accessors (stage 3)
}

superjson.registerClass(Foo, {
  identifier: "Foo",
  allowProps: ["bar"],
});

const foo = new Foo();
foo.bar = "foo";
const encoded = superjson.serialize(foo);

console.dir(encoded, { depth: null });

console.log("will deserialize");
const decoded = superjson.deserialize(encoded);
console.dir(decoded, { depth: null });

If we change

return Object.assign(Object.create(clazz.prototype), v);

into

Object.assign(new clazz(), v)

it seems to work. Of course it then has to assume constructor accepts no arguments

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions