neverthrow icon indicating copy to clipboard operation
neverthrow copied to clipboard

How to best handle Result<T, never>

Open maelp opened this issue 8 months ago • 2 comments

In order to keep all my API coherent, all my methods return Result types, but since some of those methods can't produce an error, they are typed as Result<T, never>

Then when I consume the result I'm doing eg

const myResult = await myMethod();

if (myResult.isErr()) {
    return myResult; // this doesn't type out of the box for some reason, I have to do `return myResult as Err<never, never>` to please the typecheck
}

// otherwise process
const myValue = myResult.value;

another way would be to do

const myResult = await myMethod();

// otherwise process
const myValue = myResult._unsafeUnwrap();

but the documentation says we shouldn't use unsafeUnwrap in prod code ideally

What would be the most natural way to express this:

  • I want a coherent API where all methods return a Result and therefore some are Result<T, never>
  • I want the typechecker to somehow understand that it can safely get the value of a method returning a Result<T, never> because it will never be an error?

maelp avatar Jul 28 '25 07:07 maelp

Another issue I'm having is if I'm writing a method which, say, returns Result<A, MyError>

and then I do something like

const firstResult = getSomeIntermediateValue(...); // returns Result<B, MyError>

if (firstResult.isErr()) {
    return firstResult; // this should typecheck because it's a error of type MyError
}

it doesn't work, and I have to "force" the type eg

const firstResult = getSomeIntermediateValue(...); // returns Result<B, MyError>

if (firstResult.isErr()) {
    return err(firstResult.error); // this typechecks as Result<A, MyError> although it's more verbose
}

am I doing something incorrectly?

maelp avatar Jul 28 '25 19:07 maelp

since some of those methods can't produce an error, they are typed as Result<T, never>

Can I see your myMethod function implementation. is ok(...) only thing return from your function?

SupakornNetsuwan avatar Sep 13 '25 15:09 SupakornNetsuwan