Skip to content

isErr() + early return limitations #677

@FunctionDJ

Description

@FunctionDJ

When porting a code base to use neverthrow or generally when working with non-trivial algorithms it can be desirable to use an early-return pattern.
In such cases, .map / .andThen could be too difficult to implement cleanly or result in hard-to-read code.
I think safeTry is supposed to help with this, but as of writing it's not considered safe by lint plugins (see ninoseki/eslint-plugin-neverthrow#9 ).

IsErr can be used, but if the inner result's type is incompatible with the caller's return type, the Err<T, E> must be wrapped in err(someResult.error), which feels redundant.

import { err, ok, type Result } from "neverthrow";

declare const mightError: () => Result<void, "error">;

function test(): Result<number, "error"> {
	const mightErrorResult = mightError();

	if (mightErrorResult.isErr()) {
		return mightErrorResult; // <-- type error. fix: return err(mightErrorResult.error)
	}

	return ok(5);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions