DEV Community

Cover image for The go-like Return Style is Nice and Fast
Francesco Di Donato
Francesco Di Donato

Posted on • Updated on

The go-like Return Style is Nice and Fast

Disclaimer!

I am not a professional benchmarker. If there is any error in my logic, please let me know via mail or twitter.

Source code

type Go<T> = [T, null] | [null, Error]; const [v, err] = do()

During a relaxed Friday evening consisting of lo-fi, chill, and code I found myself wanting to bring the syntax of go into typescript.

I refer to this:

v, err := do()
if err != nil {
    os.Exit(1)
}
Enter fullscreen mode Exit fullscreen mode

Trying to achieve:

const [v, err] = do()
if(err !== null) {
    process.exit(1)
}
Enter fullscreen mode Exit fullscreen mode

Implementation

type Go<T> = [T, null] | [null, Error]
Enter fullscreen mode Exit fullscreen mode

With this very simple type, it is possible to infer this kind of syntax to the return type of a function:

function do(n: number): Go<number> {
    if (isEven(n)) {
        return [n ** n, null]
    }
    return [null, new Error("number is odd")]
}
Enter fullscreen mode Exit fullscreen mode

So that when it is used you feel the nostalgia of goland:

const [v, err] = do()
Enter fullscreen mode Exit fullscreen mode

Benchmark

On my machine, the go-syntax seems to be much more fast than the try-catch & throw one.

Try it out yourself, here's the Source Code:

yarn typescript @types/node
yarn start
Enter fullscreen mode Exit fullscreen mode

Inspiration

The first time I saw this syntax was in await-to-js. This simple little library (I recommend it) achieves the same result for promises (if used in conjuction with await).
As for the synchronous world, I think this solution of mine comes closest. Although it requires explicitly writing code in a certain way -- a way, in my opinion, better than throwing stuff around :)

Top comments (1)

Collapse
 
didof profile image
Francesco Di Donato • Edited

Update

You may use something like to improve versability:

type Go<T, E extends Error = Error> = [T, null] | [null, E];
Enter fullscreen mode Exit fullscreen mode