diff --git a/src/_internals/error.ts b/src/_internals/error.ts index 6fd90f0f..8b4fb281 100644 --- a/src/_internals/error.ts +++ b/src/_internals/error.ts @@ -8,18 +8,32 @@ const defaultErrorConfig: ErrorConfig = { withStackTrace: false, } -interface NeverThrowError { - data: - | { - type: string - value: T - } - | { - type: string - value: E - } - message: string - stack: string | undefined +type ErrorData = { + type: string + value: T +} | { + type: string + value: E +} + +class NeverThrowError extends Error { + data: ErrorData + + constructor({ + data, + message, + stack, + }: { + data: ErrorData + message: string + stack: string | undefined + }) { + super(); + this.data = data; + this.message = message; + this.stack = stack; + Object.setPrototypeOf(this, new.target.prototype); + } } // Custom error object @@ -35,9 +49,9 @@ export const createNeverThrowError = ( const maybeStack = config.withStackTrace ? new Error().stack : undefined - return { + return new NeverThrowError({ data, message, stack: maybeStack, - } + }) } diff --git a/tests/index.test.ts b/tests/index.test.ts index 9f089a9d..63302bbf 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -42,6 +42,12 @@ describe('Result.Ok', () => { expect(okVal._unsafeUnwrap()).toBeUndefined() }) + it('Throws an error that is an instance of error', () => { + const okVal = ok(undefined) + + expect(() => okVal._unsafeUnwrapErr()).toThrowError(Error); + }); + it('Is comparable', () => { expect(ok(42)).toEqual(ok(42)) expect(ok(42)).not.toEqual(ok(43))