The input UnknownResult type.
The success type of the Result returned by the function.
The error type of the Result returned by the function.
The result of applying the function, or the original Err.
const parseNumber = (input: string): Result<number, string> => {
const num = Number.parseInt(input, 10);
return Number.isNaN(num) ? Result.err('not a number') : Result.ok(num);
};
const parsed = Result.flatMap(Result.ok('42'), parseNumber);
const failure = Result.flatMap(Result.ok('abc'), parseNumber);
const passthrough = Result.flatMap(Result.err('fail'), parseNumber);
assert.deepStrictEqual(parsed, Result.ok(42));
assert.deepStrictEqual(failure, Result.err('not a number'));
assert.deepStrictEqual(passthrough, Result.err('fail'));
const parseThenDouble = Result.flatMap((input: string) =>
Result.map(parseNumber(input), (value) => value * 2),
);
assert.deepStrictEqual(parseThenDouble(Result.ok('10')), Result.ok(20));
Applies a function that returns a Result to the success value of a
Result. If the input is Err, returns the original Err. This is the
monadic bind operation for Result.
The success type of the Result returned by the function.
The error type of the Result returned by the function.
The result of applying the function, or the original Err.
const parseNumber = (input: string): Result<number, string> => {
const num = Number.parseInt(input, 10);
return Number.isNaN(num) ? Result.err('not a number') : Result.ok(num);
};
const parsed = Result.flatMap(Result.ok('42'), parseNumber);
const failure = Result.flatMap(Result.ok('abc'), parseNumber);
const passthrough = Result.flatMap(Result.err('fail'), parseNumber);
assert.deepStrictEqual(parsed, Result.ok(42));
assert.deepStrictEqual(failure, Result.err('not a number'));
assert.deepStrictEqual(passthrough, Result.err('fail'));
const parseThenDouble = Result.flatMap((input: string) =>
Result.map(parseNumber(input), (value) => value * 2),
);
assert.deepStrictEqual(parseThenDouble(Result.ok('10')), Result.ok(20));
Applies a function that returns a
Resultto the success value of aResult. If the input isErr, returns the originalErr. This is the monadic bind operation forResult.