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 🙏

© 2026 – Pkg Stats / Ryan Hefner

tagged-error-kit

v0.1.1

Published

Result-agnostic tagged Error classes with exhaustive matching and bounded diagnostics

Readme

tagged-error-kit

Tagged Error classes and exhaustive matching for TypeScript.

tagged-error-kit provides a class factory for defining native errors with literal tags and typed properties. It also provides guards, exhaustive and partial matching, and bounded diagnostic output.

Install

npm install tagged-error-kit

Requires TypeScript 5.4.5 or newer and an ES2022 runtime.

Quick start

Define errors by extending the class returned by TaggedError:

import { TaggedError } from "tagged-error-kit";

class OrderNotFoundError extends TaggedError("OrderNotFoundError")<{
  orderId: string;
  message: string;
}> {}

class PaymentDeclinedError extends TaggedError("PaymentDeclinedError")<{
  reason: "insufficient-funds" | "card-expired";
  message: string;
}> {}

type CheckoutError = OrderNotFoundError | PaymentDeclinedError;

Generated instances extend Error. Their _tag is a string literal type, and constructor properties are readonly in the TypeScript type:

const error = new PaymentDeclinedError({
  reason: "insufficient-funds",
  message: "Payment was declined",
});

error instanceof Error; // true
error instanceof PaymentDeclinedError; // true
error._tag; // "PaymentDeclinedError"
error.reason; // "insufficient-funds" | "card-expired"

Call .match() on an error union with one handler for each tag:

declare const checkoutError: CheckoutError;

const response = checkoutError.match({
  OrderNotFoundError: (error) =>
    Response.json({ message: "Order not found", orderId: error.orderId }, { status: 404 }),

  PaymentDeclinedError: (error) =>
    Response.json({ message: "Payment was declined", reason: error.reason }, { status: 402 }),
});

Each handler receives the error type corresponding to its tag. Exhaustiveness is based on the static type of the matched value. If another variant is added to CheckoutError, the handler object must include that tag.

Narrow unknown errors

Every generated class has a static .is() guard. It checks whether a value is an instance of the concrete class:

declare const value: unknown;

if (PaymentDeclinedError.is(value)) {
  value.reason; // "insufficient-funds" | "card-expired"
}

Use isTaggedError() or the equivalent TaggedError.is() to check the general tagged-error contract:

import { isTaggedError } from "tagged-error-kit";

if (isTaggedError(value)) {
  console.error(value.prettyPrint());
}

isTaggedError() requires the value to be an Error with a string _tag and callable match, prettyPrint, and toJSON properties.

Standalone matching

matchError() is the standalone form of .match(). It accepts generated tagged errors and other Error values with a string _tag. Literal tag types determine the handler keys:

import { matchError } from "tagged-error-kit";

const message = matchError(checkoutError, {
  OrderNotFoundError: (error) => `Order ${error.orderId} was not found`,
  PaymentDeclinedError: (error) => `Payment failed: ${error.reason}`,
});

The return type is the union of the handler return types. Explicit type parameters can constrain every handler to one return type.

Partial matching

matchErrorPartial() handles selected variants and returns unhandled errors unchanged:

import { matchErrorPartial } from "tagged-error-kit";

const result = matchErrorPartial(checkoutError, {
  OrderNotFoundError: (error) => `Missing order: ${error.orderId}`,
});
// string | PaymentDeclinedError

An optional fallback handles the remaining variants. Its argument is narrowed to the unhandled error types:

const message = matchErrorPartial(
  checkoutError,
  {
    OrderNotFoundError: (error) => `Missing order: ${error.orderId}`,
  },
  (error) => `Payment failed: ${error.reason}`,
);

Diagnostics and logging

In Node.js, tagged errors implement the custom inspection hook used by console and node:util.inspect. The output contains the message, enumerable context properties, stack, and cause chain. prettyPrint() returns the same format:

console.error(error);
// [PaymentDeclinedError] Payment was declined
//   reason: "insufficient-funds"
//   ...native stack

JSON.stringify(new Error("message")) normally produces {} because native error fields are non-enumerable. Tagged errors implement toJSON(), which returns a depth- and size-bounded, cycle-safe diagnostic object:

error.toJSON();
// {
//   _tag: "PaymentDeclinedError",
//   name: "PaymentDeclinedError",
//   message: "Payment was declined",
//   reason: "insufficient-funds",
//   stack: "PaymentDeclinedError: Payment was declined\n..."
// }

Diagnostic output includes enumerable context and can therefore contain sensitive values. Redact those values before logging. toJSON() does not provide a transport format or deserialization contract.

API

| Export | Purpose | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | TaggedError(tag) | Create a tagged Error class with static .is() and instance .match(), prettyPrint(), and toJSON() | | isTaggedError(value) | Check the complete structural tagged-error contract | | matchError(error, handlers) | Exhaustively match a tagged error union | | matchErrorPartial(error, handlers, fallback?) | Transform selected variants and preserve or handle the rest |

Exported types: AnyTaggedError, TaggedErrorClass, and TaggedErrorInstance.

Runtime support

tagged-error-kit is ESM-only, targets ES2022, and has zero runtime dependencies. Its declared Node.js minimum is version 18. The custom console inspection behavior is Node-specific; prettyPrint() and toJSON() do not depend on that hook.

License

MIT