Skip to content

Instantly share code, notes, and snippets.

@NarHakobyan
Last active September 13, 2019 07:08
Show Gist options
  • Save NarHakobyan/381304ae3ef970397b070c7d444304ab to your computer and use it in GitHub Desktop.
Save NarHakobyan/381304ae3ef970397b070c7d444304ab to your computer and use it in GitHub Desktop.
Type safe lodash get function
function get<B, C = undefined>(func: () => B, defaultValue?: C): B | C | undefined {
try {
const value = func();
if (typeof value === 'undefined') {
return defaultValue;
}
return value;
} catch {
return defaultValue;
}
}
let a: any = {};
console.log(get(() => a.b.c));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment