A minimal implementation of the Result type in TypeScript. Allowing you to handle success and error states in a more explicit and structured way.
npm install @justmiracle/result
yarn add @justmiracle/result
pnpm add @justmiracle/result
bun add @justmiracle/result
// A result is either successful or an error
type Result<T> = Ok<T> | Err;
// A successful result contains a value and null for error
type Ok<T> = { value: T; error: null };
// An error result contains null for value and an error
type Err = { value: null; error: Error };
You can create a result using the ok
or err
function:
import { ok, err } from '@justmiracle/result';
const successResult: Result<number> = ok(42);
// { value: 42, error: null }
const errorResult: Result<number> = err(new Error('Something went wrong'));
// { value: null, error: Error }
// error can be anything, if the function detect that it's not an error it will be converted to an error
const errorResult: Result<number> = err('Something went wrong');
// { value: null, error: Error } the same as above
You can check if a result is successful using the isOk
function:
if (isOk(successResult)) {
console.log('Success:', successResult.value);
} else {
console.error('Error:', successResult.error.message);
}
You can check if a result is an error using the isErr
function:
if (isErr(errorResult)) {
console.error('Error:', errorResult.error.message);
} else {
console.log('Success:', errorResult.value);
}
You can unwrap the value from a result type using unwrapOr
, this will return the value if the result is successful or a default value if it's an error:
const resultOne = ok(42);
const value = unwrapOr(resultOne, 12); // 42
const resultTwo = err('Something went wrong');
const value = unwrapOr(resultTwo, 12); // 12 default value
You can also unwrap the value from a successful result using unwrap
, which throws an error for an error result:
Warning
This will throw an error if the result is an error, so make sure to handle it properly.
const resultOne = ok(42);
const value = unwrap(resultOne); // 42
const resultTwo = err('Something went wrong');
const value = unwrap(resultTwo); // throws an error
You can apply a function to the value inside a successful result using map
:
const successResult = ok(42);
const mappedResult = map(successResult, value => value * 2);
// { value: 84, error: null }
- Typesafe error handling
-
pipe
function
Contributions are welcome, feel free to open an issue or a pull request.🍀