A TypeScript utility library for elegant error handling with discriminated unions
The throw keyword is not explicit about what errors a function might produce, making error handling unpredictable and hard to reason about. This package provides a type-safe alternative that makes errors part of your function signatures.
- 🔒 Type-safe error handling - No more
try/catchblocks everywhere - 🎯 Discriminated unions - Clear distinction between success and error states
- 🛠 Helper functions - Easy creation and manipulation of result types
- 📦 Zero dependencies - Lightweight and focused
- 🔥 Full TypeScript support - Complete type inference and narrowing
import { asData, asError, isError, type WithError } from "."
// Define a function that might fail
const divide = (
a: number,
b: number,
): WithError<{ data: number }, { message: string }> => {
if (b === 0) {
return asError({ message: "Cannot divide by zero" })
}
return asData({ data: a / b })
}
// Use the result
const result = divide(10, 2)
if (isError(result)) {
console.error("Error:", result.message)
} else {
console.log("Result:", result.data) // TypeScript knows this is a number
}import {
asData,
asError,
isError,
type ExtractError,
type ExtractNonError,
type WithError,
} from "better-error-handling"
type ErrorFoo = { type: "foo"; message: string }
type ErrorBar = { type: "bar"; code: number }
const fetchData = (): WithError<{ something: string }, ErrorFoo | ErrorBar> => {
// Simulate different outcomes
const random = Math.random()
if (random > 0.7) {
return asError({ type: "bar", code: 500 })
}
if (random > 0.4) {
return asError({
type: "foo",
message: "An error of type foo occurred.",
})
}
return asData({ something: "All good!" })
}
const processResult = () => {
const result = fetchData()
if (isError(result)) {
if (result.type === "foo") {
console.error("Foo error:", result.message)
return
}
if (result.type === "bar") {
console.error("Bar error with code:", result.code)
return
}
}
// TypeScript knows result.something exists here
console.log("Success! Data:", result.something)
}
processResult()A discriminated union representing either success or error states.
Extracts the success type from a WithError type.
Extracts the error type from a WithError type.
Creates a successful result.
Creates an error result.
Type guard to check if a result represents an error.
MIT