diff --git a/.changeset/grumpy-hats-unite.md b/.changeset/grumpy-hats-unite.md new file mode 100644 index 00000000..dc0736d8 --- /dev/null +++ b/.changeset/grumpy-hats-unite.md @@ -0,0 +1,5 @@ +--- +'neverthrow': minor +--- + +prevent passing a specific error type for `.fromThrowable` without providing an error mapping function diff --git a/src/result-async.ts b/src/result-async.ts index 9c349c54..d9cbcfe8 100644 --- a/src/result-async.ts +++ b/src/result-async.ts @@ -42,17 +42,26 @@ export class ResultAsync implements PromiseLike> { return new ResultAsync(newPromise) } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromThrowable( + fn: (...args: A) => Promise, + ): (...args: A) => ResultAsync + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromThrowable( + fn: (...args: A) => Promise, + errorFn: (err: unknown) => E, + ): (...args: A) => ResultAsync // eslint-disable-next-line @typescript-eslint/no-explicit-any static fromThrowable( fn: (...args: A) => Promise, errorFn?: (err: unknown) => E, - ): (...args: A) => ResultAsync { + ): (...args: A) => ResultAsync { return (...args) => { return new ResultAsync( (async () => { try { return new Ok(await fn(...args)) - } catch (error) { + } catch (error: unknown) { return new Err(errorFn ? errorFn(error) : error) } })(), diff --git a/src/result.ts b/src/result.ts index 3f6f5a94..2ec2ad47 100644 --- a/src/result.ts +++ b/src/result.ts @@ -17,18 +17,33 @@ export namespace Result { * arguments but returning `Ok` if successful, `Err` if the function throws * * @param fn function to wrap with ok on success or err on failure - * @param errorFn when an error is thrown, this will wrap the error result if provided */ // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function fromThrowable any>( + fn: Fn, + ): (...args: Parameters) => Result, unknown> + /** + * Wraps a function with a try catch, creating a new function with the same + * arguments but returning `Ok` if successful, `Err` if the function throws + * + * @param fn function to wrap with ok on success or err on failure + * @param errorFn when an error is thrown, this will wrap the error result + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function fromThrowable any, E>( + fn: Fn, + errorFn: (e: unknown) => E, + ): (...args: Parameters) => Result, E> + // eslint-disable-next-line @typescript-eslint/no-explicit-any export function fromThrowable any, E>( fn: Fn, errorFn?: (e: unknown) => E, - ): (...args: Parameters) => Result, E> { + ): (...args: Parameters) => Result, E | unknown> { return (...args) => { try { const result = fn(...args) return ok(result) - } catch (e) { + } catch (e: unknown) { return err(errorFn ? errorFn(e) : e) } }