Skip to content

Instantly share code, notes, and snippets.

@mikoloism
Last active April 18, 2024 11:48
Show Gist options
  • Save mikoloism/21d7961bfbf189e48023a110906a236c to your computer and use it in GitHub Desktop.
Save mikoloism/21d7961bfbf189e48023a110906a236c to your computer and use it in GitHub Desktop.
Safest Object Getter Higher-Order Function and Clousor
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