Open lucaschultz opened 1 week ago
FYI, you can use a tag (or really any property that differentiates the 2 types) to prevent this. I would suggest instead updating the documentation to recommend this approach.
import { ok, Result, safeTry } from "neverthrow";
class MyError1 extends Error {
readonly _tag = "MyError1";
}
class MyError2 extends Error {
readonly _tag = "MyError2";
}
declare function mayFail1(): Result<number, MyError1>;
declare function mayFail2(): Result<number, MyError2>;
const test = safeTry(function* () {
yield* mayFail1();
yield* mayFail2();
return ok("Hello");
});
// const test: Result<string, MyError1 | MyError2>
In #603, @pierback mentioned that only the first
yield
is considered in thesafeTry
type inference due to a TypeScript limitation (see https://github.com/microsoft/TypeScript/issues/57625). This is a significant drawback of usingsafeTry
and should be noted in the documentation, as it can easily lead to bugs due to incomplete error handling. I'll have to check my codebases now and see wether this is an issue in my code 😌Perhaps neverthrow could include an example like this:
Including this in the
safeTry
documentation would illustrate both the issue and the expected inference ofok
values. The documentation should also emphasize that when usingsafeTry
, developers must always specify all potential errors as generics.