I avoid throwing errors in my code as they are hard to reason about. I prefer to do this:
type CanError<E> = E | undefined
function foo():CanError<Error> {
... whatever
if(bad) return new Error('did error') // error path
return undefined // success
}
const bar = foo()
if(bar!==undefined) doErrorPath(bar)
doNormalPath()
However, the risk of this approach is that I forget to handle the error path, causing weird bugs.
Is there a way one can use the Typescript compiler to force one to always handle any function that returns a value other than void as follows:
const bar = foo()
As foo
returns a value other than void the following should not be allowed:
foo()
Whilst this doesn't completely guarantee I've appropriately handled the error path, it does mean I can identify places where I for sure haven't handled the error path.