I missed Go's `if err != nil`, so I built errval for TypeScript
I write mostly TypeScript and some Go. When I switch back from Go, I miss explicit error returns. A function that can fail says so, and I deal with it right there. In TypeScript I get catch (e) , where e is unknown , thrown from some layer I forgot could throw. I wrote errval: zero dependencies, 1.86 kB minified and gzipped. const [ err , user ] = await getUser ( id ) if ( err ) return fail ( err…
The author frequently works with TypeScript and Go programming languages. They find that Go's explicit error returns stand out when they return to TypeScript, where errors are handled with catch (e) and unknown errors. This led the author to create a TypeScript package called errval, which aims to provide inferred error unions, similar to Go's approach.
errval is a lightweight library, with zero dependencies and a minified size of 1.86 kB. It allows for a cleaner handling of errors by returning them as a tuple with the value first. This approach enables the compiler to catch potential errors more effectively, as any forgotten cases in the match statement will result in a compilation error.
The author conducted a benchmark test on a Node 24.16 environment, comparing errval with other error handling methods like neverthrow, try/catch, and plain try/catch. In a scenario where half the requests fail, the execution times were as follows: neverthrow - 198 ns, errval - 226 ns, try/catch - 2,623 ns, and plain try/catch - 3,952 ns. The author notes that errval is not as fast as neverthrow but is still a viable option when dealing with inferred error unions.
The author emphasizes that the primary purpose of errval is not speed but the inferred error unions. Error construction takes 1,978 ns, while errval's error takes only 25 ns, as it avoids the overhead of the Error constructor. In TypeScript, the value comes first in the tuple ([err, value]), which helps prevent accidental dropping of the value.
However, the author acknowledges that using [err, value] in a TypeScript codebase may not be universally preferred, as it may not be as intuitive as the more common [value, err] pattern.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.