Last active
September 13, 2019 07:08
-
-
Save NarHakobyan/381304ae3ef970397b070c7d444304ab to your computer and use it in GitHub Desktop.
Type safe lodash get function
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 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