Represents the type of the Result: either Ok or Err. Useful for debugging and runtime checks.
Transforms the Result by applying a function that returns a Result to the contained Ok value, chaining multiple potentially failing operations.
The Result returned by the function if the original Result is Ok, otherwise the original Err.
const parse = (s: string) => {
const parsed = parseInt(s);
return isNaN(parsed) ? Err("NaN") : Ok(parsed);
};
const result = Ok("123").andThen(parse); // Ok(123)
const noResult = Err("NaN").andThen(parse); // Err("NaN")
Maps a Result<Ok, Err> to Result<U, Err> by applying a function to a contained Ok value, leaving an Err value untouched.
A Result containing the transformed value if Ok, or the original Err.
const length = Ok("hello").map(s => s.length); // Ok(5)
const error = Err("error").map(s => s.length); // Err("error")
Maps a Result<Ok, Err> to Result<Ok, F> by applying a function to a contained Err value, leaving an Ok value untouched.
A Result containing the original Ok, or the transformed Err.
const ok = Ok("hello").mapErr(err => `Error: ${err}`); // Ok("hello")
const error = Err("error").mapErr(err => `Error: ${err}`); // Err("Error: error")
Performs a match operation on the Result, allowing for branching logic based on its state.
The result of applying the appropriate function based on the Result's state.
const result = Ok(5).match({
ok: (val) => `Success: ${val}`,
err: (val) => `Error: ${val}`,
});
// result === "Success: 5"
const error = Err("failure").match({
ok: (val) => `Success: ${val}`,
err: (val) => `Error: ${val}`,
});
// error === "Error: failure"
Applies a function to the contained Err value if present, or returns the Ok value if present.
The original Ok if present, or the Result of the function applied to the Err value.
const ok = Ok("hello").orElse(err => Err(`Error: ${err}`)); // Ok("hello")
const error = Err("error").orElse(err => Ok(`Recovered from ${err}`)); // Ok("Recovered from error")
Returns the contained success value if Ok, otherwise returns the provided default value.
The default value to return if the Result is Err.
The contained success value if Ok, otherwise def
.
const result = Ok("value").unwrapOr("default"); // "value"
const error = Err("error").unwrapOr("default"); // "default"
The Result interface representing a success or an error. A Result is either Ok, holding a success value, or Err, holding an error value.