An immutable collection cannot be changed after it is created. To add or remove an item, create a new collection with the change instead. This avoids unexpected mutations, especially when collections are passed to APIs. section 10.4
Objects, arrays, maps, and sets are mutable by default in JavaScript. TypeScript read-only types can make them effectively immutable. Creating copies has costs: it can use more CPU and memory, and shallow copies leave nested objects shared with the original. section 10.5 section 10.4.3
Updating read-only state with Immer
A read-only state can contain an array and a map. Immer’s produce callback receives a draft that can be changed; Immer uses those changes to return a modified copy, leaving the original state intact. section 10.4.3
Listing 10.15 Applying mutations to an immutable object with Immer
import { enableMapSet, produce } from "immer";
enableMapSet(); #A
interface NinjaMetadata {
homeIsland: string;
}
type NinjaState = Readonly<{ #B
ninjas: ReadonlyArray<string>; #B
ninjaMetadata: ReadonlyMap<string, NinjaMetadata>; #B
lastModified: number; #B
}>; #B
const initialState: NinjaState = { #C
ninjas: ["Kuma", "Hattori", "Yagyu"], #C
ninjaMetadata: new Map( #C
Object.entries({ #C
Kuma: { homeIsland: "Honshu" }, #C
Hattori: { homeIsland: "Hokkaido" }, #C
}), #C
), #C
lastModified: Date.now(), #C
}; #C
const getStateWithNewNinja = (
previousState: NinjaState,
newNinja: string,
newNinjaMetadata: NinjaMetadata,
): NinjaState => {
return produce(previousState, (state) => { #D
state.ninjas.push(newNinja); #D
state.ninjaMetadata.set(newNinja, newNinjaMetadata); #D
state.lastModified = Date.now(); #D
}); #D
};
const nextState = getStateWithNewNinja( #E
initialState, #E
"Yoshi", #E
{ homeIsland: "Yoshi's Island" }, #E
); #E
console.assert(
nextState.ninjas.length ===
initialState.ninjas.length + 1,
"Added a new ninja",
);
console.assert(
nextState.ninjaMetadata.size ===
initialState.ninjaMetadata.size + 1,
"Added metadata for the new ninja",
);
See a TypeScript example that declares read-only state and uses Immer to add a ninja and update its metadata. section 10.4.3





























