Minimalist, strongly-typed result pattern for TypeScript
npm install resultxA lightweight and simple Result type for TypeScript, inspired by Rust's Result type.
resultx provides a Result type that represents either success (Ok) or failure (Err). It helps to handle errors in a more explicit and type-safe way, without relying on exceptions.
For error handling in synchronous code, resultx provides a trySafe function that wraps a function that might throw an error. For asynchronous code, trySafe can also be used with promises.
- 🎭 Simple and intuitive Result type, wrapping Ok and Err values
- 🚀 Supports both synchronous and asynchronous operations
- 🛡️ Type-safe error handling
- 🧰 Zero dependencies
- 📦 Tiny bundle size (half a kilobyte minified)
- Installation
- Usage
- API
- Examples
Add resultx to your dependencies by running one of the following commands, depending on your package manager:
``bash
pnpm add -D resultx
Usage
`ts
import { err, ok, trySafe, unwrap } from 'resultx'// Create
Ok and Err results
const successResult = ok(42)
// ^? Ok
const failureResult = err('Something went wrong')
// ^? Err<"Something went wrong">// Use
trySafe for error handling
const result = trySafe(() => {
// Your code that might throw an error
return JSON.parse('{"foo":"bar"}')
})// Either log the result or the error
if (result.ok) {
console.log('Parsed JSON:', result.value)
}
else {
console.error('Failed to parse JSON:', result.error)
}
// Or unwrap and destructure the result
const { value, error } = unwrap(result)
`API
$3
The
Result type represents either success (Ok) or failure (Err).Type Definition:
`ts
type Result = Ok | Err
`####
OkThe
Ok type wraps a successful value.Example:
`ts
const result = new Ok(42)
`Type Definition:
`ts
declare class Ok {
readonly value: T
readonly ok: true
constructor(value: T)
}
`$3
The
Err type wraps an error value.Example:
`ts
const result = new Err('Something went wrong')
`Type Definition:
`ts
declare class Err {
readonly error: E
readonly ok: false
constructor(error: E)
}
`$3
Shorthand function to create an
Ok result. Use it to wrap a successful value.Type Definition:
`ts
function ok(value: T): Ok
`$3
Shorthand function to create an
Err result. Use it to wrap an error value.Type Definition:
`ts
function err(err: E): Err
function err(err: E): Err
`$3
Wraps a function that might throw an error and returns a
Result with the result of the function.Type Definition:
`ts
function trySafe(fn: () => T): Result
function trySafe(promise: Promise): Promise>
`$3
Unwraps a
Result, Ok, or Err value and returns the value or error in an object. If the result is an Ok, the object contains the value and an undefined error. If the result is an Err, the object contains an undefined value and the error.Example:
`ts
const result = trySafe(() => JSON.parse('{"foo":"bar"}'))
const { value, error } = unwrap(result)
`Type Definition:
`ts
function unwrap(result: Ok): { value: T, error: undefined }
function unwrap(result: Err): { value: undefined, error: E }
function unwrap(result: Result): { value: T, error: undefined } | { value: undefined, error: E }
`Examples
$3
A common use case for
Result is error handling in functions that might fail. Here's an example of a function that divides two numbers and returns a Result:`ts
import { err, ok } from 'resultx'function divide(a: number, b: number) {
if (b === 0) {
return err('Division by zero')
}
return ok(a / b)
}
const result = divide(10, 2)
if (result.ok) {
console.log('Result:', result.value)
}
else {
console.error('Error:', result.error)
}
`$3
The
trySafe function is useful for error handling in synchronous code. It wraps a function that might throw an error and returns a Result:`ts
import { trySafe } from 'resultx'const result = trySafe(() => JSON.parse('{"foo":"bar"}'))
if (result.ok) {
console.log('Parsed JSON:', result.value)
}
else {
console.error('Failed to parse JSON:', result.error)
}
`$3
For asynchronous operations,
trySafe can also be used with promises. Here's an example of fetching data from an API:`ts
import { trySafe } from 'resultx'async function fetchData() {
const result = await trySafe(fetch('https://api.example.com/data'))
if (result.ok) {
const data = await result.value.json()
console.log('Fetched data:', data)
}
else {
console.error('Failed to fetch data:', result.error)
}
}
fetchData()
``MIT License © 2023-PRESENT Johann Schopplich