Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Set Object.prototype with spread operator

Using the spread operator is a succinct way to compose an object consisting of an aggregation of other objects' properties.

But is there succinct and performant way to set the prototype of an object with the spread operator?

Currently I have:

const result = Object.assign(Object.create(EmailCampaign.prototype), properties) 

. . . which spreads the properties returned from a database query into an object with the EmailCampaign prototype. Is there a way to set the object prototype with the spread operator?

This would be possible:

const result = Object.setPrototypeOf({...properties}, EmailCampaign.prototype);

. . however it is inadvisable with regards to performance to set the prototype of an object after instantiation. I'm looking for another way, if one exists.

like image 948
Jasper Blues Avatar asked Jun 15 '26 00:06

Jasper Blues


1 Answers

Using Object.assign+Object.create is the proper and performant solution. You should use it. If you want to make it more concise, use a helper function that combines the two.

That said, calling Object.setPrototypeOf on an object literal is not that slow, as the object was not yet used elsewhere.

Is there a way to set the object prototype with the spread operator?

Well if you want to use an officially deprecated feature, you can use the __proto__ property in an object intialiser:

const result = {__proto__: EmailCampaign.prototype, ...properties};

So yes, it's possible, but I would definitely not recommend it.

like image 164
Bergi Avatar answered Jun 16 '26 13:06

Bergi



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!