TypeScript from zero: copy before you change a field
An object spread copies the fields and replaces one. The original latte stays 450 cents. The tipped copy is 540. The program prints 450 540.
Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.
const item = { cents: 450 } stops you from assigning a new object to item. It does not freeze the fields. item.cents = 540 still changes the object, and every other name for that object sees the tip baked into the menu price. The tip: copy the object, change the copy, and leave the original alone.
The binding and the object are different#
const item freezes the binding. It does not freeze the object. item.cents = 540 would change the same object everyone else is holding, and the checker allows it because the property is mutable. The spread { ...item, cents: 540 } allocates a new object, copies the own enumerable properties, and overwrites cents. 540 is 450 plus a 20 percent tip. item.cents stays 450. The copy is one level deep. A nested object would still be shared. This item is flat, so the split is complete.
- item450
- tipped540
const item = { name: "latte", cents: 450 };
const tipped = { ...item, cents: 540 };
console.log(item.cents, tipped.cents);
450 540
The spread writes a new object#
...item copies name and cents into a new object. cents: 540 then replaces cents on that new object. item.cents is still 450. tipped.cents is 540. console.log prints both. The menu stays $4.50. The bill is $5.40.
This matters in React because state is the old object. You build the next one and hand it back. Mutating item.cents and calling setState with the same object gives React the value it already had, and the screen does not update. The copy is a different object, so the update is visible.
Nested objects are not copied deep#
...item copies the fields. If a field is itself an object, both copies share that inner object. A drink this small has only a string and a number, so the copy is complete. When a field is an array or another object, copy that field too before you change it. The next lesson uses a union so a value can be one of two shapes, and the checker makes you handle both.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.