neverthrow-pattern v0.1.0
Description
neverthrow-pattern
bridges the gap between two powerful TypeScript libraries: neverthrow
and ts-pattern
. It provides a seamless integration layer that allows you to use pattern matching with the Result type from neverthrow, making your error handling code more expressive, concise, and type-safe.
import { match } from "ts-pattern";
import { NP } from "neverthrow-pattern";
import { Result, ok, err } from "neverthrow";
const handleResult = (result: Result<number, string>) =>
match(result)
.with(NP.ok(), (value) => `Success: ${value.value}`)
.with(NP.ok(42), () => "The answer is 42!")
.with(NP.err(P.string), (error) => `Error: ${error.value}`)
.exhaustive();
// Usage
handleResult(ok(42)); // "The answer is 42!"
handleResult(ok(7)); // "Success: 7"
handleResult(err("Something went wrong")); // "Error: Something went wrong"
Features
- 🎯 Pattern match on neverthrow's Result type: Use expressive pattern matching for both
Ok
andErr
values - 🛡️ Type-safe: Full type inference and exhaustiveness checking
- 🧩 Composable patterns: Combine with other ts-pattern patterns for complex matching scenarios
- 🔍 Pattern validation: Match on the inner value of
Ok
andErr
instances - 📝 Comprehensive type definitions: Works seamlessly with TypeScript
- 🔄 Match type interoperability: Enhances the standard match function to work with neverthrow Results
Installation
# Using pnpm
pnpm add neverthrow-pattern
# Using yarn
yarn add neverthrow-pattern
# Using npm
npm install neverthrow-pattern
Make sure you have both neverthrow
and ts-pattern
installed:
pnpm add neverthrow ts-pattern
Usage
Importing
// Import everything under a namespace (recommended)
import { NP } from "neverthrow-pattern";
// Import match and other utilities from ts-pattern
import { match, P } from "ts-pattern";
// Import from neverthrow as usual
import { Result, ok, err } from "neverthrow";
Basic Pattern Matching on Result
Match on any Ok
or Err
value:
const processResult = (result: Result<number, string>) =>
match(result)
.with(NP.ok(), ({ value }) => `Got success with value: ${value}`)
.with(NP.err(), ({ error }) => `Got error: ${error}`)
.exhaustive();
Pattern Matching with Value Validation
Match on specific values inside Ok
or Err
:
const processApiResult = (
result: Result<
{ status: "success" | "pending"; data: unknown },
{ code: number; message: string }
>
) =>
match(result)
.with(
NP.ok({ status: "success" }),
({ value }) => `Success: ${JSON.stringify(value.data)}`
)
.with(NP.ok({ status: "pending" }), () => "Operation in progress...")
.with(NP.err({ code: 404 }), () => "Not found")
.with(
NP.err({ code: P.number.gt(500) }),
({ error }) => `Server error: ${error.message}`
)
.with(NP.err({ code: P.number }), ({ error }) => `Error: ${error}`)
.exhaustive();
Using with ts-pattern's Other Patterns
Combine with other patterns from ts-pattern:
match(result)
.with(NP.ok(P.when((n) => n > 10)), () => "Got a number greater than 10")
.with(NP.ok(), ({ value }) => `Got: ${value}`)
.with(NP.err(P.string), ({ error }) => `Error message: ${error}`)
.with(NP.err(P.any), () => "Some other error")
.exhaustive();
Pattern Selection
Note: Currently, using
P.select()
insideNP.ok()
andNP.err()
patterns is not supported. For example,NP.ok(P.select())
orNP.err(P.select())
won't work as expected. This feature may be implemented in a future version.
Enhanced Match Type Interoperability
The library enhances the standard match function to work better with neverthrow Results.
When using neverthrow-pattern, the match
function from ts-pattern is automatically enhanced to work better with Result types. This means:
- You don't need any special imports or setup - just import the library and start using it
- The type system correctly distributes union types within Results for precise pattern matching
- Type inference works properly when destructuring Ok and Err values
API Documentation
Main Functions
NP.ok<input, pattern>(pattern?)
: Creates a pattern that matches Ok valuesNP.err<input, pattern>(pattern?)
: Creates a pattern that matches Err values
Both functions can be used:
- Without arguments to match any Ok/Err value
- With a pattern to match against the inner value
Type Definitions
UnwrapOk<T>
: Extracts the success type from a ResultUnwrapErr<T>
: Extracts the error type from a Result
For complete API documentation, please refer to the generated TypeDoc documentation.
Contributing
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b my-new-feature
- Make your changes
- Create a changeset to document your changes:
pnpm changeset
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request
Please make sure your code follows the existing style and includes appropriate tests.
For more detailed information, see the CONTRIBUTING.md guide.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- neverthrow - A type-safe alternative to throwing exceptions
- ts-pattern - The exhaustive Pattern Matching library for TypeScript
- All contributors who have helped improve this library
Built with ❤️ for type-safe error handling in TypeScript.
4 months ago