I am working with an array of Results
coming from the neverthrow library. My goal is to check if there are any errors in the array and if so, terminate my function. However, the challenge arises when there are no errors present, as I then want to destructure the array into the corresponding Ok
types since it's guaranteed that an Err
cannot exist at that point.
Let me illustrate the issue with an example:
import { Err, ok, Result } from "neverthrow";
function resultIsError(
result: Result<unknown, Error>
): result is Err<unknown, Error> {
return result.isErr();
}
function doSomething() {
const results = [
ok(true) as Result<boolean, Error>,
ok("foobar") as Result<string, Error>,
ok({ foo: "bar" }) as Result<{ foo: string }, Error>
];
const resultErrors = results.filter(resultIsError);
if (resultErrors.length > 0) {
return resultErrors;
}
const [someBool, someString, someObj] = results;
const someBoolValue: boolean = someBool.value;
const someStringValue: string = someString.value;
const someObjValue: { foo: string } = someObj.value;
}
The problem surfaces when attempting to access .value
, triggering this error message:
Property 'value' does not exist on type 'Err<boolean, Error>'
It seems that Typescript is unable to recognize that Err
cannot possibly exist in this scenario. Is there a more elegant and straightforward approach to handle this issue?
To visualize the problem, I have set up a codesandbox: https://codesandbox.io/s/wild-architecture-nivu94?file=/src/index.ts:9-12