Best practice for object cloning (in TS)?
Looking to get deep copies of things like EmbedBuilder.
structuredClone doesn't copy functions. Should we be doing something like const secondEmbed = new EmbedBuilder({...firstEmbed})?16 Replies
node ver is 22.12.0
djs ver is 14.24.2
typescript ver is 5.9.3
is
firstEmbed an EmbedBuilder?Yeah, a previously defined EmbedBuilder with fields, description, contents, or whatever else previously set.
I want to be able to make a clone and modify it without side effects polluting the prior embed.
then just set
Will assignment provide a deep copy by value by default? So if I e.g. tamper with secondEmbed's fields after that, they won't change firstEmbed?
that is my understanding
Thank you. Will test it out RQ and see.
So I tried two things:
First:
This did not work. It tainted the prior EmbedBuilder object.
Second, I tried the same thing, but replacing with , and that worked as expected.
However, I am looking for a more general, idiomatic way to accomplish this more uniformly across various objects in the discord.js library.
this would be another was to go from APIdata to builder
Cool, the #from method looks like it might be used across some other classes like ActionRowBuilder, so that might be the idiom some of the devs want us to use.
Just tested and it works the same way as cloning from data. Good stuff. Thank you.
glad #from worked out
went an looked up the source code it is pretty simple
In VS Code when I hit f12 on EmbedBuilder to hop to implementation, I see this:
How'd you wind up landing on that piece of the source? Trying to figure out if there's a convenient way for me to jump there.
Short of like going into node_modules and navigating the tree by hand.
Grabbing the code from the code link on https://discord.js.org/docs/packages/discord.js/14.24.2/EmbedBuilder:Class#from ?
discord.js
discord.js
discord.js is a powerful Node.js module that allows you to interact with the Discord API very easily. It takes a much more object-oriented approach than most other JS Discord libraries, making your bot's code significantly tidier and easier to comprehend.
ya got it from the docs code link
Good to know. Thank you!