Skip to content

Instantly share code, notes, and snippets.

@crabmusket
Last active May 18, 2023 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crabmusket/14c84d1fa87cb1b45337fe8bb9d83872 to your computer and use it in GitHub Desktop.
Save crabmusket/14c84d1fa87cb1b45337fe8bb9d83872 to your computer and use it in GitHub Desktop.
Immer-like updates with explicit keys
// Modify an object, passing an explicit key array. The callback only has access to the keys in the array.
function modify<T, K extends keyof T>(instance: T, keys: K[], update: (v: Pick<T, K>) => void) {
const draft = structuredClone(instance);
update(draft);
// for example's sake, just log the changed keys
for (let k of keys) {
console.log("updated", k, "from", instance[k], "to", draft[k]);
}
}
const value = Object.freeze({a: 1, b: "4", c: false});
modify(value, ["a", "b"], draft => {
draft.a = 2;
// NOT ALLOWED
//draft.c = true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment