ESLint Plugin for NeverThrow
The eslint-plugin-neverthrow ensures that Result and ResultAsync values are properly handled in your codebase, preventing unhandled errors from slipping through.
Overview
Created by mdbetancourt as part of NeverThrow’s bounty program, this ESLint plugin enforces that errors are not left unhandled.
This plugin is essentially a porting of Rust’s must-use attribute to TypeScript/JavaScript.
Installation
Install the plugin via npm:
Or using other package managers:
Configuration
Add the plugin to your ESLint configuration file:
Using Flat Config (ESLint 9+)
Using Legacy Config (.eslintrc)
Rules
must-use-result
This rule ensures that Result and ResultAsync values are consumed in one of the following ways:
- Calling
.match()
- Calling
.unwrapOr()
- Calling
._unsafeUnwrap() (for test environments)
This guarantees that you’re explicitly handling the error case of your Result.
Valid Patterns
The following patterns are considered valid:
Using match
Using unwrapOr
Using _unsafeUnwrap in Tests
Chaining Operations
Invalid Patterns
The following patterns will trigger ESLint errors:
Not Consuming the Result
Only Handling Success Case
Ignoring Async Results
Fixing Violations
When the plugin reports a violation, you have three options to fix it:
Option 1: Use match
Handle both success and error cases explicitly:
Option 2: Use unwrapOr
Provide a default value for the error case:
Option 3: Use _unsafeUnwrap (Tests Only)
For test environments where you’re confident about the result:
_unsafeUnwrap() should only be used in test environments. It will throw if the Result is an Err.
Integration with Type Checking
The plugin works alongside TypeScript’s type system to provide comprehensive safety:
Working with Async Code
The plugin also validates ResultAsync handling:
Configuration Options
The plugin can be configured with different severity levels:
Best Practices
Enable in All Environments
Enable the plugin in all environments except tests, where you might legitimately use _unsafeUnwrap:
Combine with TypeScript Strict Mode
For maximum type safety, use the plugin alongside TypeScript’s strict mode:
Use with Pre-commit Hooks
Integrate the plugin with pre-commit hooks to catch issues early:
External Resources
Have questions or suggestions? Join the discussion: