@byteslice/result

中文文档
0.5.0发布于 2026/06/29TypeScriptESM + CJS零依赖近 30 天下载 1.3万

A lightweight TypeScript utility for wrapping operations in a structured Result type, mitigating the need for exception-handling boilerplate.

原始使用文档
文档目录15 节
  1. Table of Contents
  2. Motivation
  3. Errors vs. Exceptions
  4. Function Signatures
  5. Success and Failure States
  6. Overview
  7. Usage
  8. Basic Example
  9. Custom Failure
  10. Hook: onException
  11. Unwrapping: unwrap and expect
  12. Fallbacks: unwrapOr and unwrapOrElse
  13. Transforming: map and mapFailure
  14. Contributing
  15. License

@byteslice/result

A lightweight TypeScript utility for wrapping operations in a structured Result type, mitigating the need for exception-handling boilerplate.

This package enables developers to clearly represent both success and failure states, ensuring a predictable and type-safe approach to managing operation results.

🍕 Built by the team at ByteSlice.

Table of Contents

Motivation

To fully understand the purpose and application of this package, it's essential to provide some context.

Errors vs. Exceptions

Exceptions are particularly useful in scenarios where a program must terminate quickly in response to serious problems or unforeseen circumstances. As the term suggests, they signify exceptions that arise when standard operations are disrupted by the unexpected.

In TypeScript, any value can be "thrown" as an exception: errors, strings, numbers, you name it. This is why "caught" exceptions are type unknown.

Errors, on the other hand, are values that represent anticipated—albeit undesired—behavior. They denote an error state and typically contain a descriptive message that explains the nature of the problem.

Function Signatures

TypeScript—while providing excellent type safety—lacks a built-in mechanism to indicate when a function might throw an exception.

Consider the following function. While the implementation indicates that an exception could be thrown, the type signature fails to convey this information.

function fetchUser(id: string): User {
  throw new Error('Oh no, Mr. Bill!')
}

This becomes especially problematic if the developer is not familiar with the underlying implementation. They may need to resort to defensive try/catch blocks or risk having exceptions propagate unexpectedly.

Success and Failure States

Every operation can lead to one of two possible outcomes: success or failure. Establishing a standard pattern to represent both of these potential states is crucial.

The @byteslice/result package provides this pattern through a Result type that effectively captures these two distinct states.

Instead of an operation simply returning a value (indicating success) or throwing an exception (indicating failure), it can return a type-safe Result that represents either outcome.

Overview

@byteslice/result provides the following exports:

  1. Result – A discriminated union type representing either:

    • Success: { data: S }
    • Failure: { failure: F }
  2. withResult – An asynchronous function wrapper that:

    • Executes a provided operation.
    • Catches any thrown exception.
    • Returns a success or failure object rather than throwing.
  3. unwrap / expect – Escape hatches (inspired by Rust) that return the success data directly, or throw if the Result is a failure.

  4. unwrapOr / unwrapOrElse – Total (non-throwing) extractors that return the success data, or a fallback when the Result is a failure.

  5. map / mapFailure – Combinators (inspired by Rust) that transform the success data or the failure while passing the other state through untouched.

This pattern is particularly helpful when you want to avoid using try/catch directly in your code, or if you need a standardized way to capture failure details.

Usage

Basic Example

import { withResult } from '@byteslice/result'

// function signature does not indicate an exception may occur
async function fetchData(): Promise<string> {
  throw new Error('The dog refused to fetch')
}

async function main() {
  const result = await withResult(
    // operation
    () => fetchData(),
    // onError
    (error) => new Error('Could not fetch data', { cause: error })
  )

  // check for failure
  if (result.failure) {
    console.error(result.failure)
  } else {
    // result is a success
    // data property is now available
    console.log(result.data)
  }
}

main()

🔎  Let's examine withResult further:

  • The first parameter (operation) wraps a function to be executed when withResult is called.
    • If the provided function throws an exception, it is coerced to an error (as necessary).
  • The second parameter (onError) receives this error as its sole argument and returns a FailureOption—either an Error or a FailureCase (an object with an error property).
  • The Result returned from withResult depends on the result of the operation.
    • If successful, the returned Result will be type Success and contain the output of the executed function in its data property.
    • If unsuccessful, the returned Result will be type Failure and contain the FailureOption in its failure property.

To ensure failure states are handled, the failure property of the Result must be examined before the data property (and its strongly-typed contents) can be accessed.

💡 In the example above, onError returns a bespoke Error while maintaining the stack trace of the original error via cause.

Custom Failure

By default, the Failure type of Result contains a failure property of Error.

However, you can define your own custom failure—as long as it is an object with an error property of type Error. This ensures the error is available, while permitting the flexibility to add any other fields.

import { withResult, Result } from '@byteslice/result'

type CustomFailure = {
  // required property
  error: Error
  // custom property
  type: 'NETWORK_ERROR' | 'VALIDATION_ERROR'
}

type CustomSuccess = { name: string }

async function fetchUser(): Promise<Result<CustomSuccess, CustomFailure>> {
  return await withResult(
    async () => {
      // function call may throw an exception
      const name = await db.getName()

      return { name }
    },
    // onError returns custom failure
    (error) => ({ error, type: 'NETWORK_ERROR' })
  )
}

async function main() {
  const result = await fetchUser()

  if (result.failure) {
    console.warn('This type of error occurred:', result.failure.type)
  } else {
    console.log(result.data.name)
  }
}

main()

Hook: onException

You can optionally provide an onException hook to transform the original exception into an error before it is passed to onError. This is a great spot for logging or returning custom errors based on the type of exception.

import { withResult } from '@byteslice/result'

async function main() {
  const result = await withResult(
    // operation may throw an exception
    () => riskyOperation(),
    // onError receives error returned from onException
    (err) => (err),
    {
      onException: (ex) => {
        // log thrown exception
        console.warn('Caught exception:', ex)

        // return known error
        if (err instanceof CustomError) {
          return err
        }

        // return default error
        return new Error('Something unexpected occurred')
      }
    }
  )

  if (result.failure) {
    console.error(result.failure)
  } else {
    console.log(result.data)
  }
}

main()

If no onException hook is provided, then any thrown exceptions are handled by an internal ensureError function. As the name implies, it ensures the onError hook receives a valid error.

Unwrapping: unwrap and expect

Inspecting the failure property is the safe, type-driven way to consume a Result. Occasionally, however, you know an operation should have succeeded and simply want the underlying data—treating any failure as an exceptional, program-halting event.

Borrowing from Rust's Result, unwrap and expect provide this escape hatch.

unwrap returns the success data, or re-throws the failure's underlying error.

import { unwrap, withResult } from '@byteslice/result'

const result = await withResult(
  () => fetchData(),
  (error) => error,
)

// returns the data on success, or throws the underlying error on failure
const data = unwrap(result)

expect behaves the same, but lets you describe why a success was expected. On failure it throws an Error with your message, preserving the original error via cause.

import { expect, withResult } from '@byteslice/result'

const result = await withResult(
  () => loadConfig(),
  (error) => error,
)

// throws `Error('config should be present', { cause: <original error> })` on failure
const config = expect(result, 'config should be present')

⚠️ Like their Rust counterparts, unwrap and expect trade type safety for convenience. Reach for them only when a failure genuinely represents an unrecoverable state.

Fallbacks: unwrapOr and unwrapOrElse

When a failure should resolve to a sensible default rather than an exception, unwrapOr and unwrapOrElse return the success data or a fallback—and never throw.

unwrapOr takes an eager fallback value.

import { unwrapOr, withResult } from '@byteslice/result'

const result = await withResult(
  () => loadTimeout(),
  (error) => error,
)

// returns the loaded timeout, or 5000 on failure
const timeout = unwrapOr(result, 5000)

unwrapOrElse takes a function that computes the fallback from the failure. It is only invoked when the result is a failure, making it the lazy counterpart to unwrapOr.

import { unwrapOrElse, withResult } from '@byteslice/result'

const result = await withResult(
  () => loadConfig(),
  (error) => error,
)

// computes a fallback from the failure, only when needed
const config = unwrapOrElse(result, (failure) => {
  console.warn('Falling back to defaults:', failure.message)
  return defaultConfig
})

Transforming: map and mapFailure

map and mapFailure transform one side of a Result while passing the other side through untouched, letting you compose transformations without manually unpacking and re-packing the Result.

map transforms the success data. A failure is returned unchanged, and the mapping function is not invoked.

import { map, withResult } from '@byteslice/result'

const result = await withResult(
  () => fetchUser(),
  (error) => error,
)

// Result<User, Error> → Result<string, Error>
const name = map(result, (user) => user.name)

💡 The mapping function is assumed to be infallible (it cannot itself fail). If your transformation may throw, wrap it in withResult instead.

mapFailure transforms the failure. A success is returned unchanged, and the mapped failure must itself be a valid failure—either an Error or an object with an error property.

import { mapFailure, withResult } from '@byteslice/result'

const result = await withResult(
  () => fetchUser(),
  (error) => error,
)

// enrich the failure with additional context
const tagged = mapFailure(result, (error) => ({
  error,
  type: 'NETWORK_ERROR' as const,
}))

Contributing

Please see CONTRIBUTING.md for details.

License

MIT © ByteSlice See the LICENSE file for more details.

版本与发布记录

@byteslice/result 共发布 8 个版本,首次发布于 2024/09/06;过去 12 个月发布了 2 个版本。

版本发布日期距今
0.5.0latest2026/06/294 个月前
0.4.02026/06/294 个月前
0.3.02025/08/211.2 年前
0.2.22025/03/101.7 年前
0.2.12025/03/101.7 年前
0.2.02025/02/261.7 年前

关于 @byteslice/result 的常见问题

@byteslice/result 是什么?

A lightweight TypeScript utility for wrapping operations in a structured Result type, mitigating the need for exception-handling boilerplate.

如何安装 @byteslice/result?

在项目目录运行 npm install @byteslice/result,或使用 pnpm add / yarn add / bun add。

@byteslice/result 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@byteslice/result 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@byteslice/result 可以商用吗?

@byteslice/result 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@byteslice/result 的下载量有多少?

根据 npm 官方下载统计,@byteslice/result 在 2026/10/09 – 2026/11/07 这 30 天内被下载 13,303 次,日均约 443 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@byteslice/result 还在维护吗?

最新版本 0.5.0 发布于 2026/06/29(4 个月前);至今共发布 8 个版本,其中过去 12 个月发布了 2 个;首次发布于 2024/09/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。