Created
January 25, 2018 17:26
-
-
Save alexsasharegan/e37b404cd49bc757abf42d23b2dd4b39 to your computer and use it in GitHub Desktop.
Go-like error handling with Typescript.
This file contains 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 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
I find adding
!
to every use ofvalue
very annoying so I think a better approach is to just check for!value
instead oferror
. This way you will be able to usevalue
without!
every time while keeping the same end result.