Last active
September 16, 2022 19:48
-
-
Save oxwazz/cb558e45fa4593b58447d94dad5a38c1 to your computer and use it in GitHub Desktop.
[TypeScript] Safe 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
export const safeFunc = <T extends (...args: any[]) => any>( | |
func: T, | |
args: Parameters<T>, | |
defaultValue: ReturnType<T> | |
): [error: any, data: ReturnType<T>] => { | |
try { | |
const data = func(...args) | |
return [null, data] | |
} catch (e) { | |
return [e, defaultValue] | |
} | |
} | |
export const safeFuncAsync = async <T extends (...args: any[]) => Promise<any>>( | |
func: T, | |
args: Parameters<T>, | |
defaultValue: ReturnType<T> | |
): Promise<[error: any, data: Awaited<ReturnType<T>> | ReturnType<T>]> => { | |
try { | |
const data = await func(...args) | |
return [null, data] | |
} catch (e) { | |
return [e, defaultValue] | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment