Immutable Updates and Copying
Nested Copies
Nested data needs a copy at each level that changes.
Nested Copies
nested.ts
type Address = {
city: string;
country: string;
};
type Profile = {
name: string;
address: Address;
};
const nextCity: string = ;
const profile: Profile = {
name: "Ada",
address: { city: "London", country: "UK" },
};
const moved: Profile = {
...profile,
address: { ...profile.address, city: nextCity },
};
console.log(`before=${profile.address.city}`);
console.log(`after=${moved.address.city}`);
type Address = {
city: string;
country: string;
};
type Profile = {
name: string;
address: Address;
};
const nextCity: string = ;
const profile: Profile = {
name: "Ada",
address: { city: "London", country: "UK" },
};
const moved: Profile = {
...profile,
address: { ...profile.address, city: nextCity },
};
console.log(`before=${profile.address.city}`);
console.log(`after=${moved.address.city}`);
type Address = {
city: string;
country: string;
};
type Profile = {
name: string;
address: Address;
};
const nextCity: string = ;
const profile: Profile = {
name: "Ada",
address: { city: "London", country: "UK" },
};
const moved: Profile = {
...profile,
address: { ...profile.address, city: nextCity },
};
console.log(`before=${profile.address.city}`);
console.log(`after=${moved.address.city}`);
nested copy
When a nested object changes, copy the outer object and the inner object so unchanged references stay separate from updated data.