npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

rusty-result-kit

v0.0.2

Published

Lightweight Result<T, E> helpers like Rust's Result for modeling fallible TypeScript code without exceptions.

Readme

rusty-result-kit

English Document

rusty-result-kit 是一个轻量的 Result<T, E> 容器,帮助你在 TypeScript 项目里显式描述成功与失败的结果,而不用处处抛异常,同时保留 Rust Result 的使用体验。

特性

  • 基于判别属性的成功 / 失败容器,读取状态清晰 (ok / err)。
  • 同时支持同步与异步代码:fromfromAsyncfromPromise 帮你捕获异常或拒绝。
  • 提供丰富的链式工具(mapmapErrmapAsync)与兜底方法(unwrapunwrapOrexpect)。
  • 无额外运行时依赖,内置 ESM、CJS、UMD、IIFE 多种构建格式与类型声明。

安装

任选常用的包管理器:

pnpm add rusty-result-kit
# 或者
yarn add rusty-result-kit
# 或者
npm install rusty-result-kit

快速上手

将可能抛错的逻辑包装成 Result,让调用方显式处理失败场景:

import { Result } from 'rusty-result-kit';

function parseCount(input: string): Result<number, Error> {
  return Result.from(() => {
    const value = Number.parseInt(input, 10);
    if (Number.isNaN(value)) {
      throw new Error('count 必须是数字');
    }
    return value;
  });
}

const count = parseCount('3')
  .map((value) => value * 2)
  .unwrapOr(0); // -> 6

const fallback = parseCount('oops').unwrapOr(0); // -> 0

显式处理错误

把异步流程转成 Result,无需再写「try/catch 套 try/catch」:

const result = await Result.fromAsync(async () => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('请求失败');
  }
  return response.json();
});

const data = result.match({
  ok: (value) => value,
  err: (error) => {
    console.error(error);
    return null;
  },
});

模式匹配与副作用

利用链式函数保持逻辑的声明式风格:

const message = Result.from(() => maybeFailingSyncWork())
  .inspect((value) => console.log('success', value))
  .inspectErr((error) => console.warn('error', error))
  .match({
    ok: (value) => `Finished with ${value}`,
    err: (error) => `Could not finish: ${error.message}`,
  });

如果只关心布尔值,isOkAndisErrAnd 会自动收窄类型:

const result = Result.from(() => findUser(id));

if (result.isOkAnd((user) => user.isActive)) {
  // 在此分支中 `user` 会被推断为活跃用户
}

API 概览

静态方法

| 方法 | 说明 | | --- | --- | | Result.ok(value) | 包装一个成功值。 | | Result.err(error) | 包装一个错误载荷。 | | Result.from(fn) | 捕获同步函数抛出的异常。 | | Result.fromAsync(fn) | 捕获异步函数抛出的异常或拒绝。 | | Result.fromPromise(promise) | 将现有 Promise 转成 Result。 |

实例方法

| 方法 | 说明 | | --- | --- | | okerrorvalue | 访问内部状态。 | | mapmapAsync | 转换成功分支。 | | mapErr | 转换失败分支。 | | unwrapunwrapOrexpect | 以不同兜底方式取出成功值。 | | match | 在成功 / 失败间进行穷尽式分支。 | | inspectinspectErr | 执行副作用但返回原始结果。 | | isOkAndisErrAnd | 返回布尔并收窄承载的类型。 | | [Symbol.iterator] | 需要时可解构为 [value, error]。 |

类型提示

错误类型完全由你自定义,可用于表达更具体的领域错误:

type ParseError =
  | { kind: 'invalid-number'; input: string }
  | { kind: 'negative-number'; input: number };

function parsePositiveInt(input: string): Result<number, ParseError> {
  return Result.from(() => {
    const parsed = Number.parseInt(input, 10);
    if (Number.isNaN(parsed)) {
      throw { kind: 'invalid-number', input } satisfies ParseError;
    }
    if (parsed < 0) {
      throw { kind: 'negative-number', input: parsed } satisfies ParseError;
    }
    return parsed;
  });
}

parsePositiveInt 之后继续链式调用时,会一直保持 Result<number, ParseError> 推断,从而保证编译期的正确性。

分发形式

包内提供多种构建产物,可根据你的工具链自由选择:

  • 默认导出为 ESM(import)。
  • CommonJS 使用 require('rusty-result-kit')
  • 浏览器可直接通过 rusty-result-kit/umd 使用 UMD 版本。
  • 临时脚本场景可以引入 rusty-result-kit/iife 的 IIFE 构建文件。
  • 所有类型声明都位于 rusty-result-kitrusty-result-kit/index.d.ts

实现本身体积小且无副作用,打包工具能很好地进行 tree shaking。