← Catalog

@mypolis.eu/result

A lightweight, type-safe `Result<T, E>` type for TypeScript, inspired by Go's explicit error handling and Rust's Result type. Zero dependencies.

Package

Install

Install with PiG

pig install npm:@mypolis.eu/result

Install with Pi

pi install npm:@mypolis.eu/result
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "skills": [
    "./skills"
  ]
}

README

Written by the package's publisher, shown as published in version 0.10.0 (README.md). PiG does not review it.

@mypolis.eu/result

A lightweight, type-safe Result<T, E> type for TypeScript, inspired by Go's explicit error handling and Rust's Result type. Zero dependencies.

Why?

TypeScript's try/catch doesn't tell you what can fail. Functions that throw hide their error types from the caller, and forgetting a try/catch leads to uncaught exceptions.

With Result, errors are just return values. The type system tracks them and forces you to handle both cases.

Installation

npm install @mypolis.eu/result

Agent skill

The package includes an agent skill with the rules for using Result well: skills/result/SKILL.md. Agents use it when they write, review, or refactor code that returns Result.

Install it in pi with:

pi install npm:@mypolis.eu/result

Then use /skill:result, or let the agent load the skill when it works with Result.

Core Types

Result<T, E>

type Result<T, E> = { ok: true; value: T; error: null } | { ok: false; value: null; error: E }

A discriminated union. Check result.ok and TypeScript narrows the type automatically. The two branches are exported as OkResult<T> and ErrResult<E>.

Err<K, C>

type Err<K extends string, C = unknown> = {
	kind: K
	message?: string
	cause?: C
}

Define one type for each error. The name is Err<Module><Subject><State>, and the kind is the same name in kebab-case without the prefix:

import { type Err } from "@mypolis.eu/result"

type ErrAuthEmailInvalid   = Err<"auth-email-invalid">
type ErrAuthEmailDuplicate = Err<"auth-email-duplicate">
type ErrAuthTokenExpired   = Err<"auth-token-expired">
type ErrAuthCodeInvalid    = Err<"auth-code-invalid">

Do not group errors into a union alias. Write the errors that a function can return in its signature.

Type helpers

type ResultValue<R> // the T of a Result type
type ResultErr<R>   // the E of a Result type
type WithError<R, E> // R with E added to its error type

Use these only on a generic R, for example in a unit of work that adds a database error to whatever its callback returns:

interface UnitOfWork {
	execute<R extends Result<unknown, { kind: string }>>(
		work: (repositories: Repositories) => Promise<R>,
	): Promise<WithError<R, ErrDatabaseQueryFailed>>
}

Primary Pattern: Imperative Check and Return

This is the Go-inspired style: check for errors and propagate them explicitly. It's the recommended default for most code.

Scenario: User Registration

import { type Err, type Result, ok, err, wrapAsync } from "@mypolis.eu/result"
import * as v from "valibot"

// Define domain errors
type ErrAuthEmailInvalid    = Err<"auth-email-invalid">
type ErrAuthEmailDuplicate  = Err<"auth-email-duplicate">
type ErrAuthUserCreateFailed = Err<"auth-user-create-failed">

// Validation layer: returns Result
function validateEmail(input: string): Result<string, ErrAuthEmailInvalid> {
	const parsed = v.safeParse(v.pipe(v.string(), v.email()), input)
	if (!parsed.success) {
		return err({
			kind: "auth-email-invalid",
			message: `"${input}" is not a valid email`,
			cause: parsed.issues,
		})
	}
	return ok(parsed.output)
}

// Database layer: returns Result via wrapAsync
async function insertUser(
	email: string,
): Promise<Result<User, ErrAuthEmailDuplicate | ErrAuthUserCreateFailed>> {
	return wrapAsync(
		() => db.user.create({ data: { email } }),
		(cause): ErrAuthEmailDuplicate | ErrAuthUserCreateFailed => {
			if (isDuplicateError(cause)) {
				return { kind: "auth-email-duplicate", message: "Email already registered", cause }
			}
			return { kind: "auth-user-create-failed", message: "User creation failed", cause }
		},
	)
}

// Compose them: check and propagate
async function registerUser(
	email: string,
): Promise<Result<User, ErrAuthEmailInvalid | ErrAuthEmailDuplicate | ErrAuthUserCreateFailed>> {
	const validEmail = validateEmail(email)
	if (!validEmail.ok) return validEmail

	const user = await insertUser(validEmail.value)
	if (!user.ok) return user

	return ok(user.value)
}

Key points:

  • Each function declares exactly what can go wrong in its return type
  • Error propagation is explicit: if (!result.ok) return result
  • The caller of registerUser can't forget to handle errors; the type enforces it
  • Unexpected errors (bugs) still throw; they aren't domain errors

Handling errors: switch and unreachable

At an IO boundary (HTTP handler, job, CLI), handle each kind with a switch. End it with default: return unreachable(e). Send a public code to the client, never message or cause, and log the error where it stops:

import { formatError, unreachable } from "@mypolis.eu/result"

// HTTP route handler
router.post("/register", async (req) => {
	const result = await registerUser(req.body.email)
	if (result.ok) return json(result.value, 201)

	const e = result.error
	switch (e.kind) {
		case "auth-email-invalid":
			return json({ code: "AUTH_EMAIL_INVALID" }, 400)
		case "auth-email-duplicate":
			return json({ code: "AUTH_EMAIL_DUPLICATE" }, 409)
		case "auth-user-create-failed":
			logger.error({ error: e }, formatError(e))
			return json({ code: "TEMPORARILY_UNAVAILABLE" }, 503)
		default:
			return unreachable(e)
	}
})
  • If a kind is not handled, the compiler reports an error at unreachable(e)
  • Without unreachable, a missing kind can compile. For example, a Result<void, E> function falls through to return ok(undefined) and reports success
  • unreachable throws if it runs, for example when an untyped value reaches it

match

match converts a Result into one value by handling both branches:

const label = match(result, {
	ok: (user) => user.email,
	err: (e) => formatError(e),
})

mapErr

When a low-level function returns technical errors, translate them into domain errors for the layer above. Keep the original error in cause. The kind that the mapper returns stays a literal type:

type ErrDbTimeout          = Err<"db-timeout">
type ErrDbConnectionFailed = Err<"db-connection-failed">
type ErrOrderUnavailable   = Err<"order-unavailable">

// Low-level: returns technical errors
function findOrder(id: string): Result<Order, ErrDbTimeout | ErrDbConnectionFailed>

// Service layer: translates to domain error
function getOrder(id: string): Result<Order, ErrOrderUnavailable> {
	return mapErr(findOrder(id), (cause) => ({
		kind: "order-unavailable",
		message: "Could not retrieve order",
		cause,
	}))
}

The happy path passes through untouched. Only the error is transformed. Translate only errors that lead the caller to the same action. Here, the caller retries in both cases.

wrap / wrapAsync

Use wrap to safely call functions that may throw: third-party libs, JSON.parse, fs operations, Valibot/Zod parsing without safeParse. Always pass a mapError, so the error type is not unknown. Use wrapAsync for async functions, because wrap does not catch a rejection:

import { wrap, wrapAsync } from "@mypolis.eu/result"

type ErrConfigInvalid     = Err<"config-invalid">
type ErrConfigUnavailable = Err<"config-unavailable">

// Synchronous: JSON.parse
function parseConfig(raw: string): Result<AppConfig, ErrConfigInvalid> {
	return wrap(
		() => JSON.parse(raw) as AppConfig,
		(cause) => ({ kind: "config-invalid", message: "Invalid config JSON", cause }),
	)
}

// Async: external API call
async function fetchRemoteConfig(): Promise<Result<AppConfig, ErrConfigUnavailable>> {
	return wrapAsync(
		() => fetch("https://api.example.com/config").then((r) => r.json()),
		(cause) => ({ kind: "config-unavailable", message: "Failed to fetch config", cause }),
	)
}

map

Less commonly needed. Extracts or reshapes a success value without leaving the Result:

// Without map
const sub = findActiveSubscription(userId)
if (!sub.ok) return sub
const plan = sub.value.plan

// With map: same thing in one line
const plan = map(findActiveSubscription(userId), (sub) => sub.plan)

Prefer the if-style when the transform is complex or when it improves readability.

unwrap

unwrap extracts the value, or throws an Error with the failure in cause. The message is formatError(error). Use it only where there's no caller to propagate to:

// CLI entry point: crash on failure
function main() {
	const config = unwrap(loadConfig())
	startServer(config)
}

// Tests: the assertion is the point
test("valid email passes validation", () => {
	const result = validateEmail("user@example.com")
	const email = unwrap(result)
	expect(email).toBe("user@example.com")
})

In business logic, check the Result and handle each kind:

const result = await getCart(cartId)
if (!result.ok) return result
const cart = result.value

assertError: Testing

Asserts that a Result is an error with a specific kind. Narrows the type so the error variant is fully accessible. It is in a separate entry point, because it uses node:assert:

import { assertError } from "@mypolis.eu/result/testing"

test("duplicate email returns auth-email-duplicate", async () => {
	const result = await registerUser("existing@example.com")
	assertError(result, "auth-email-duplicate")
	// result.error is narrowed to ErrAuthEmailDuplicate
	expect(result.error.message).toContain("already registered")
})

For the success case, use unwrap. It returns the value on success and throws (which fails the test) on error:

import { unwrap } from "@mypolis.eu/result"

test("valid registration succeeds", async () => {
	const result = await registerUser("new@example.com")
	const user = unwrap(result)
	expect(user.email).toBe("new@example.com")
})

Anti-Patterns

The agent skill has the full list of rules. The most common problems are:

  • Don't group errors into an alias. type ShippingClientError = ErrA | ErrB | ... hides which errors a function can really return.

  • Don't alias Result. type ShippingResult<T> = Result<T, ...> hides the error type. Always write Result<T, E>.

  • Don't use generic kinds. "database-error" or "unknown-error" do not tell the caller what went wrong.

  • Don't throw inside Result-returning functions. If something is truly unexpected (bug, invariant violation), let it propagate naturally. Use wrap only at the boundary to call throw-based code.

  • Don't discard an error. if (!result.ok) return null makes a database failure look like "no data". Check the kind first.

  • Don't send message or cause to a client. Map each kind to a public code.

  • Don't overuse combinators. If map or mapErr makes the code harder to read than an if-statement, use the if-statement.

Migrating to 0.10

From 0.8:

  • Error<K> is now Err<K>, and the kind is required.
  • ResultError<R> is now ResultErr<R>.
  • The branch types Ok<T> and Err<E> are now OkResult<T> and ErrResult<E>.

From 0.9:

  • The deprecated Error and ResultError aliases are removed.
  • assertError moved to @mypolis.eu/result/testing.
  • isErr is removed.
  • unwrap and unwrapAsync have no default value parameter. They throw an Error whose cause is the failure, not the failure itself.
  • err accepts only an object with a kind.
  • unreachable is new.

License

MIT