ConstReadonlyok: <ResultType, ErrorType extends Error = Error>(Creates a successful Result containing the provided value. The value can be of any type, including null and undefined.
const stringValue = result.ok("Hello");
const numberValue = result.ok(42);
const objectValue = result.ok({ name: "John", age: 30 });
const nullValue = result.ok(null);
const undefinedValue = result.ok(undefined);
// All of these are Ok Results
console.log(stringValue.is_ok()); // true
console.log(numberValue.value_or(0)); // 42
Readonlyerror: <ResultType, ErrorType extends Error = Error>(Creates a failed Result containing the provided error. The error must be an instance of Error or a subclass of Error.
const basicError = result.error(new Error("Basic error"));
const typeError = result.error<string, TypeError>(new TypeError("Wrong type"));
const customError = result.error(new RangeError("Out of range"));
// Explicitly typed error results
const parseError: Result<number, Error> = result.error<number, Error>(new Error("Parse failed"));
const validationError = result.error<User, ValidationError>(new ValidationError("Invalid data"));
// All of these are Error Results
console.log(basicError.is_error()); // true
if (typeError.is_error()) {
console.log(typeError.error.message); // "Wrong type"
}
// Custom error classes work too
class ValidationError extends Error {
field: string;
constructor(message: string, field: string) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
Readonlyok_async: <ResultType, ErrorType extends Error = Error>(Creates an AsyncResult that has already resolved to an Ok Result. Useful for synchronous functions that must return AsyncResult because one or more branches invoke async code.
Readonlyerror_async: <ResultType, ErrorType extends Error = Error>(Creates an AsyncResult that has already resolved to an Error Result. Useful for synchronous functions that must return AsyncResult because one or more branches invoke async code.
Readonlytry: {Readonlytry_async: {Readonlyretry: <ValueType, ErrorType extends Error>(Retries a result-returning function until it succeeds or has failed for all of the requested retries. If the function returns an Ok Result, the retry operation stops and returns that successful Result. If the function returns an Error Result, it's retried up to the specified number of times. If all retries fail, returns an Error Result containing all the accumulated errors.
let attempts = 0;
function unreliableOperation(): Result<string, Error> {
attempts++;
if (attempts < 3) {
return result.error(new Error(`Attempt ${attempts} failed`));
}
return result.ok("Success!");
}
const retryResult = result.retry(unreliableOperation, 5);
if (retryResult.is_ok()) {
console.log(retryResult.value); // "Success!"
}
// Network request example
function fetchData(): Result<string, Error> {
// Simulated network request that might fail
return Math.random() > 0.7
? result.ok("Data fetched successfully")
: result.error(new Error("Network timeout"));
}
const networkResult = result.retry(fetchData, 3);
networkResult.match({
on_ok: (data) => console.log("Got data:", data),
on_error: (error) => console.log("All retries failed:", error.errors.map(e => e.message))
});
// Can be chained with other Result operations
const processedResult = result.retry(fetchData, 3)
.map(data => data.toUpperCase())
.and_then(data => data.includes("SUCCESS") ? result.ok(data) : result.error(new Error("Invalid data")));
Readonlyretry_async: <ValueType, ErrorType extends Error>(Retries a Promise
let attempts = 0;
async function unreliableAsyncOperation(): Promise<Result<string, Error>> {
attempts++;
await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async work
if (attempts < 3) {
return result.error(new Error(`Async attempt ${attempts} failed`));
}
return result.ok("Async success!");
}
const retryResult = await result.retry_async(unreliableAsyncOperation, 5);
if (retryResult.is_ok()) {
console.log(retryResult.value); // "Async success!"
}
// Network request example
async function fetchDataAsync(): Promise<Result<string, Error>> {
return result.try_async(async () => {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.text();
return result.ok(data);
})
}
const networkResult = await result.retry_async(fetchDataAsync, 3);
networkResult.match({
on_ok: (data) => console.log("Got data:", data),
on_error: (error) => console.log("All retries failed:", error.errors.map(e => e.message))
});
// Can be chained with other Result operations
const processedResult = await result.retry_async(fetchDataAsync, 3)
.then(res => res.map(data => data.toUpperCase()))
.then(res => res.and_then(data =>
data.includes("SUCCESS") ? result.ok(data) : result.error(new Error("Invalid data"))
));
import { result, type Result } from "./result.ts";
// Creating success results
const success = result.ok("Hello, World!");
const number = result.ok(42);
const nullValue = result.ok(null);
// Creating error results
const failure = result.error(new Error("Something went wrong"));
const customError = result.error(new TypeError("Type mismatch"));
// Chaining operations
const processed = result.ok(" hello ")
.map(str => str.trim())
.map(str => str.toUpperCase())
.and_then(str => str.length > 0 ? result.ok(str) : result.error(new Error("Empty string")));
Factory functions for creating Result instances. This module provides the primary API for constructing Result values.