gitmyhub

neverthrow

TypeScript ★ 7.6k updated 4mo ago

Type-Safe Errors for JS & TypeScript

TypeScript library that replaces throw/catch error handling with explicit Result types, errors become part of function return types so the compiler warns you when you forget to handle a failure case.

TypeScriptJavaScriptnpmESLintsetup: easycomplexity 2/5

NeverThrow is a TypeScript library that changes how you handle errors in JavaScript and TypeScript code. In most JavaScript programs, errors are thrown as exceptions using try/catch blocks, which can be easy to forget and hard to track through a codebase. NeverThrow takes a different approach borrowed from languages like Rust: instead of throwing, functions return a Result value that is explicitly either a success (Ok) or a failure (Err). Your code then checks which one it got and handles both cases deliberately.

The practical effect is that errors become part of your function's return type, so the TypeScript compiler can warn you if you forget to handle a failure case. You can chain operations together: if one step succeeds, the next step runs; if any step fails, the failure passes through automatically without you writing nested conditionals. This style is sometimes called railway-oriented programming or functional error handling.

The library covers both regular (synchronous) functions and async operations. For async work, it provides a ResultAsync class that wraps a Promise but gives you all the same chaining and checking methods. You can also convert existing functions that throw exceptions into ones that return Results, which is useful for wrapping third-party libraries.

An optional companion package called eslint-plugin-neverthrow adds a lint rule that forces you to actually handle every Result your code produces, similar to a compiler feature in Rust. This prevents you from silently ignoring errors.

Installation is a single npm command. The README is extensive and documents every method with signatures and examples. The library is aimed at TypeScript developers who want stricter, more explicit error handling without relying on exceptions. The full README is longer than what was shown.

Where it fits