Last active
April 18, 2024 11:48
-
-
Save mikoloism/21d7961bfbf189e48023a110906a236c to your computer and use it in GitHub Desktop.
Safest Object Getter Higher-Order Function and Clousor
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
function typeSafeGetter<V extends object>(o: V) { | |
return function < | |
K extends keyof V, | |
P extends undefined | K = undefined, | |
R = P extends K ? V[P] : V, | |
>(property?: P): R { | |
if (typeof o === 'undefined') throw 'error'; | |
if (typeof property === 'undefined') { | |
return o as never | |
} else return o[property] as never | |
} | |
} | |
type O = { | |
display: 'flex' | 'block', | |
dir: 'rtl' | 'ltr', | |
}; | |
declare const o: O; | |
const get = typeSafeGetter(o); | |
get('dir') === 'ltr'; | |
get().dir === 'ltr'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment