Last active
May 18, 2023 07:17
-
-
Save crabmusket/14c84d1fa87cb1b45337fe8bb9d83872 to your computer and use it in GitHub Desktop.
Immer-like updates with explicit keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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