Created
June 4, 2020 17:06
-
-
Save alanthai/2f2180bffedc24c70abba3e232fb402f to your computer and use it in GitHub Desktop.
Typesafe getter and setter
This file contains hidden or 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
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