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.2

Published

A utility package for handling try-catch blocks in TypeScript.

Readme

cowboy trying to catch a horse npm version npm downloads

Type-Safe Try-Catch Pattern for TypeScript

A lightweight TypeScript utility that provides type-safe error handling through a functional approach. This library allows you to explicitly define error types while maintaining full TypeScript inference and zero runtime overhead.

Installation

npm install @shkumbinhsn/try-catch

Key Features

  • 🔒 Type Safety: Explicitly declare what errors your functions can throw
  • 🎯 Zero Runtime Overhead: Types are compile-time only using TypeScript's structural typing
  • 🔄 Async/Sync Support: Works seamlessly with both synchronous and asynchronous functions
  • 📦 Lightweight: Minimal footprint with no dependencies
  • 🧠 Smart Inference: Falls back to standard TypeScript inference when no error types are specified
  • 🛡️ Tuple-based: Returns [data, error] tuples for explicit error handling

Why Use This Pattern?

Traditional try-catch blocks in TypeScript don't provide type information about what errors might be thrown. This library solves that by:

  1. Making error types explicit in function signatures
  2. Forcing explicit error handling through tuple destructuring
  3. Providing better IntelliSense and type checking
  4. Maintaining compatibility with existing code

Example Code

Defining a Function with Error Handling

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

class CustomError extends Error {}

function iMightFail(): string & Throws<CustomError> {
  const random = Math.random();
  if (random > 0.2) {
    return "success";
  } else if (random > 0.5) {
    throw new CustomError("Something went wrong");
  }
  throw new Error("Generic error");
}

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

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

Async Functions with Errors

async function fetchUserData(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 data");
  }
  
  return response.json();
}

const [userData, error] = await tryCatch(() => fetchUserData("123"));

if (error) {
  if (error instanceof ValidationError) {
    console.log("Validation error:", error.message);
  } else if (error instanceof NetworkError) {
    console.log("Network error:", error.message);
  } else {
    console.log("Unexpected error:", error.message);
  }
} else {
  console.log("User data:", userData);
  // TypeScript knows: userData is User
}

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) {
  console.log("Operation failed:", error.message);
  // TypeScript knows: error is Error
} else {
  console.log("Operation succeeded:", data);
  // TypeScript knows: data is string
}

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.

Usage:

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

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

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

License

MIT