Skip to content

Instantly share code, notes, and snippets.

@alanthai
Created June 4, 2020 17:06
Show Gist options
  • Save alanthai/2f2180bffedc24c70abba3e232fb402f to your computer and use it in GitHub Desktop.
Save alanthai/2f2180bffedc24c70abba3e232fb402f to your computer and use it in GitHub Desktop.
Typesafe getter and setter
type Key = string | number | symbol
const PathSymbol = Symbol('path');
function pathProxy(path: Key[] = []) {
return new Proxy({
get [PathSymbol]() {
return path;
},
}, {
get: (target, prop) => {
if (prop === PathSymbol) {
return target[prop];
}
return pathProxy(target[PathSymbol].concat(prop));
}
});
}
export function setter<T, V>(fn: (state: T) => V, value: V): (state: T) => T {
const proxy = fn(pathProxy()) as any;
return lodashSet(proxy[PathSymbol], value) as any;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment