Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Created January 25, 2018 17:26
Show Gist options
  • Save alexsasharegan/e37b404cd49bc757abf42d23b2dd4b39 to your computer and use it in GitHub Desktop.
Save alexsasharegan/e37b404cd49bc757abf42d23b2dd4b39 to your computer and use it in GitHub Desktop.
Go-like error handling with Typescript.
export async function wrapErr<T>(p: Promise<T>): Promise<[any, T | undefined]> {
try {
return [undefined, await p];
} catch (err) {
return [err, undefined];
}
}
let [err, value] = await wrapErr(somePromiseFunc());
if (err) {
console.error(err)
return;
}
// TS thinks the value can still be undefined,
// but we know that if we didn't have an error,
// the value is defined.
// The ! postfix operator tells TS it's defined.
use(value!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment