Skip to content

Instantly share code, notes, and snippets.

@jasonblanchard
Last active April 30, 2023 17:22
Show Gist options
  • Save jasonblanchard/fbd5ebdef8ab5f1e1c16b405c9009c2c to your computer and use it in GitHub Desktop.
Save jasonblanchard/fbd5ebdef8ab5f1e1c16b405c9009c2c to your computer and use it in GitHub Desktop.
typescript result types
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function wrap<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => Result<ReturnType<T>> {
return function(...args: Parameters<T>): Result<ReturnType<T>> {
try {
const value = fn(...args);
return {
ok: true,
value,
}
} catch (error) {
return {
ok: false,
error: error as Error,
}
}
}
}
function wrapAsync<T extends (...args: any[]) => Promise<any>>(fn: T): (...args: Parameters<T>) => Promise<Result<ReturnType<T>>> {
return async function(...args: Parameters<T>): Promise<Result<ReturnType<T>>> {
try {
const value = await fn(...args);
return {
ok: true,
value,
}
} catch (error) {
return {
ok: false,
error: error as Error,
}
}
}
}
async function doSomethingAsync(arg: string) {
return arg;
}
async function main() {
// const result = wrap(JSON.parse)("asdf")
// if (!result.ok) {
// console.error("uh oh", result.error)
// return;
// }
// console.log(result.value);
const asyncResult = await wrapAsync(doSomethingAsync)('my arg')
if (!asyncResult.ok) {
console.error("uh oh async", result.error)
return
}
console.log(asyncResult.value)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment