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

@shkumbinhsn/try-catch

v0.0.8

Published

A utility package for handling try-catch blocks in TypeScript with full type inference.

Downloads

783

Readme

@shkumbinhsn/try-catch

npm version npm downloads

Type-safe error handling for TypeScript using a functional [data, error] tuple pattern.

Installation

npm install @shkumbinhsn/try-catch

Features

  • Type Safety: Explicitly declare what errors your functions can throw
  • Zero Runtime Overhead: Types are compile-time only
  • Async/Sync Support: Works with both synchronous and asynchronous functions
  • Lightweight: No dependencies, minimal footprint
  • Tuple-based: Returns [data, error] for explicit error handling

Usage

Basic Example

import { tryCatch, type Throws } from "@shkumbinhsn/try-catch";

class CustomError extends Error {
  name = "CustomError" as const;
}

function riskyOperation(): string & Throws<CustomError> {
  if (Math.random() > 0.5) {
    throw new CustomError("Something went wrong");
  }
  return "success";
}

const [data, error] = tryCatch(() => riskyOperation());

if (error) {
  // TypeScript knows: error is Error | CustomError
  console.error("Failed:", error.message);
} else {
  // TypeScript knows: data is string
  console.log("Success:", data);
}

Async Functions

import { tryCatch, type Throws } from "@shkumbinhsn/try-catch";

class ValidationError extends Error {}
class NetworkError extends Error {}

async function fetchUser(id: string): Promise<User> & Throws<ValidationError | NetworkError> {
  if (!id) {
    throw new ValidationError("User ID is required");
  }
  
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new NetworkError("Failed to fetch user");
  }
  
  return response.json();
}

// Async usage
const [user, error] = await tryCatch(() => fetchUser("123"));

if (error) {
  if (error instanceof ValidationError) {
    console.error("Validation failed:", error.message);
  } else if (error instanceof NetworkError) {
    console.error("Network failed:", error.message);
  }
} else {
  console.log("User:", user.name);
}

Using tc() for Inferred Return Types

When you want TypeScript to infer your return type but still declare possible errors, use the tc() helper:

import { tryCatch, tc } from "@shkumbinhsn/try-catch";

class APIError extends Error {}
class NetworkError extends Error {}

function fetchUser() {
  const user = { id: "1", name: "Ada", email: "[email protected]" };
  // Return type is inferred as { id: string; name: string; email: string } & Throws<APIError | NetworkError>
  return tc(user).mightThrow<APIError | NetworkError>();
}

const [data, error] = tryCatch(fetchUser);

if (error) {
  // TypeScript knows: error is Error | APIError | NetworkError
  console.error("Failed:", error.message);
} else {
  // TypeScript knows: data is { id: string; name: string; email: string }
  console.log("User email:", data.email);
}

Without Explicit Error Types

When you don't specify error types, the library falls back to standard TypeScript inference:

function regularFunction() {
  return "success";
}

const [data, error] = tryCatch(regularFunction);

if (error) {
  // TypeScript knows: error is Error
  console.error("Failed:", error.message);
} else {
  // TypeScript knows: data is string
  console.log("Success:", data);
}

API Reference

tryCatch<T>(fn: () => T): TryCatchReturn<T>

Executes a function within a try-catch block and returns a result tuple.

Parameters:

  • fn: Function to execute (can be sync or async)

Returns:

  • [data, null] on success
  • [null, error] on failure

Throws<T extends Error>

Type utility for declaring error types in function signatures.

function myFunction(): ReturnType & Throws<MyError> {
  // implementation
}

tc<T>(value: T): TcBuilder<T>

Creates a builder for branding return values with error types.

function myFunction() {
  const result = computeSomething();
  return tc(result).mightThrow<ErrorA | ErrorB>();
}

Limitations

  • Duplicate Definitions: Error types must be declared in both the throw statement and return type
  • Runtime Validation: No runtime enforcement of declared error types
  • Learning Curve: Requires understanding of TypeScript's structural typing

ESLint Plugin

For automated enforcement of best practices, use the companion ESLint plugin:

npm install -D @shkumbinhsn/try-catch-eslint

See @shkumbinhsn/try-catch-eslint for details.

License

MIT