@badrap/result

中文文档
0.3.1发布于 2025/08/04MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 12万

A TypeScript result type taking cues from Rust's Result and Haskell's Either types

原始使用文档
文档目录10 节
  1. Installation
  2. Usage
  3. API
  4. Result.ok / Result.err
  5. Result#isOk / Result#isErr
  6. Result#unwrap
  7. Result#map
  8. Result#chain
  9. Result.all
  10. License

@badrap/result CI npm

A TypeScript result type taking cues from Rust's Result and Haskell's Either types. It's goals are:

  • Small, idiomatic API surface: Mix and match parts from Rust's Result and Haskell's Either types, but modify them to make the experience TypeScript-y (TypeScriptic? TypeScriptalicious?). Of course this is pretty subjective.
  • Coding errors should throw: While Result#map and Result#chain together somewhat resemble Promise#then but differ in that they don't implicitly wrap errors thrown in callbacks.
  • Be ergonomic but safe: Leverage TypeScript's type inference to make common cases simple while keeping type safety. This also helps to get a nice editor experience in e.g. Visual Studio Code.

Installation

$ npm i @badrap/result

Usage

import { Result } from "@badrap/result";

API

Result<T, E extends Error = Error> is a type that wraps either a value that is the result of a succesful computation and of type T, or an error of type E denoting a failed computation.

The type is actually an union of two types: Result.Ok<T, E> that wraps a success value and Result.Err<T, E> that wraps an error.

Result.ok / Result.err

Result.ok returns a new Result.Ok wrapping the given value, while Result.err returns a new Result.Err wrapping the given error.

const res = Result.ok(1);
res.isOk; // true

const res = Result.err(new Error());
res.isOk; // false

const res = Result.err(); // functionally equal to Result.err(new Error())
res.isOk; // false

Result.Ok has an additional property value containing the wrapped value. Similarly, Result.Err has the property error containing the wrapped error. They can be accessed after asserting to TypeScript's type checker that it's safe to do so. The isErr and isOk properties (see below) are handy for this.

const res = Math.random() < 0.5 ? Result.ok(1) : Result.err(new Error("oh no"));

if (res.isErr) {
  // TypeScript now knows that res is a Result.Err, and we can access res.error
  res.error; // Error("oh no")
}

if (res.isOk) {
  // TypeScript now knows that res is a Result.Ok, and we can access res.value
  res.value; // 1
}

Result#isOk / Result#isErr

Result#isOk and Result#isErr are complementary readonly properties. isOk is true for Result.Ok and false for Result.Err.

const ok = Result.ok(1);
ok.isOk; // true

const err = Result.err(new Error());
err.isOk; // false

isErr is the inverse of isOk: false for Result.Ok and true for Result.Err.

const ok = Result.ok(1);
ok.isErr; // false

const err = Result.err(new Error());
err.isErr; // true

Result#unwrap

Return the wrapped value for Result.Ok and throw the wrapped error for Result.Err. This can be modified for providing functions to map the value and error to some value.

const ok = Result.ok(1);
const err = Result.err(new Error("oh no"));

ok.unwrap(); // 1
err.unwrap(); // throws Error("oh no")

ok.unwrap((value) => value + 1); // 2
err.unwrap((value) => value + 2); // throws Error("oh no")

ok.unwrap(
  (value) => value + 1,
  (error) => 0,
); // 2
err.unwrap(
  (value) => value + 2,
  (error) => 0,
); // 0

As a small extra convenience the result types from the callbacks don't have to be the same. Here's an example Koa.js handler demonstrating this, using an imaginary validate function that returns a Result:

app.use(async ctx =>
  await validate(ctx.request.body).unwrap(
    async (value: any) => {
      ...
    },
    error => {
      ctx.status = 422;
      ctx.body = {
        message: "validation failed"
      };
    }
  )
);

Result#map

Return a new Result where the given function/functions have been applied to the wrapped value and error.

const ok = Result.ok(1);
const err = Result.err(new Error("oh no"));

ok.map((value) => value + 1).unwrap(); // 2
err.map((value) => value + 1).unwrap(); // throws Error("oh no")

ok.map(
  (value) => value + 1,
  (error) => new Error("mapped"),
).unwrap(); // 2
err
  .map(
    (value) => value + 1,
    (error) => new Error("mapped"),
  )
  .unwrap(); // throws Error("mapped")

Result#chain

const ok = Result.ok(1);
const err = Result.err(new Error("oh no"));

ok.chain((value) => Result.ok(value + 1)).unwrap(); // 2
err.chain((value) => Result.ok(value + 1)).unwrap(); // throws Error("oh no")

ok.chain(
  (value) => Result.ok(value + 1),
  (error) => Result.ok(0),
).unwrap(); // 2
err
  .chain(
    (value) => Result.ok(value + 1),
    (error) => Result.ok(0),
  )
  .unwrap(); // 0

Result.all

Return a new Result where the wrapped value is the collection of the wrapped values of the input array.

Result.all([Result.ok(1), Result.ok("test")]).unwrap(); // [1, "test"]

If any of the input results wraps an error then that result is returned as-is.

Result.all([Result.ok(1), Result.err(new Error("oh no"))]).unwrap(); // throws Error("oh no")

Non-array objects can also be given as arguments. In that case the wrapped output value is also an object.

Result.all({
  x: Result.ok(1),
  y: Result.ok("test"),
}).unwrap(); // { x: 1, y: "test" }

License

This library is licensed under the MIT license. See LICENSE.

版本与发布记录

@badrap/result 共发布 17 个版本,首次发布于 2018/10/19;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.1latest2025/08/041.3 年前
0.3.02025/08/041.3 年前
0.2.132022/10/204 年前
0.2.122022/05/054 年前
0.2.112022/05/054 年前
0.2.102022/05/054 年前

关于 @badrap/result 的常见问题

@badrap/result 是什么?

A TypeScript result type taking cues from Rust's Result and Haskell's Either types

如何安装 @badrap/result?

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

@badrap/result 支持 TypeScript 吗?

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

@badrap/result 支持 ESM 还是 CommonJS?

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

@badrap/result 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@badrap/result 可以商用吗?

@badrap/result 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

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

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

@badrap/result 还在维护吗?

最新版本 0.3.1 发布于 2025/08/04(1.3 年前);至今共发布 17 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/10/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。