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!)
@mp3por
Copy link

mp3por commented Jul 13, 2024

I find adding ! to every use of value very annoying so I think a better approach is to just check for !value instead of error. This way you will be able to use value without ! every time while keeping the same end result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment