diff --git a/src/result.ts b/src/result.ts index 5bcd8c5..f5ff398 100644 --- a/src/result.ts +++ b/src/result.ts @@ -133,11 +133,17 @@ export class ErrImpl implements BaseResult { } expect(msg: string): never { - throw new Error(`${msg} - Error: ${toString(this.val)}\n${this._stack}`); + // The cause casting required because of the current TS definition beign overly restrictive + // (the definition says it has to be an Error while it can be anything). + // See https://github.com/microsoft/TypeScript/issues/45167 + throw new Error(`${msg} - Error: ${toString(this.val)}\n${this._stack}`, { cause: this.val as any }); } unwrap(): never { - throw new Error(`Tried to unwrap Error: ${toString(this.val)}\n${this._stack}`); + // The cause casting required because of the current TS definition beign overly restrictive + // (the definition says it has to be an Error while it can be anything). + // See https://github.com/microsoft/TypeScript/issues/45167 + throw new Error(`Tried to unwrap Error: ${toString(this.val)}\n${this._stack}`, { cause: this.val as any }); } map(_mapper: unknown): Err { diff --git a/test/err.test.ts b/test/err.test.ts index f7aa085..bec02cd 100644 --- a/test/err.test.ts +++ b/test/err.test.ts @@ -53,17 +53,27 @@ test('else, unwrapOr', () => { }); test('expect', () => { - expect(() => { + try { const err = Err(true).expect('should fail!'); expect_never(err, true); - }).toThrowError('should fail!'); + throw new Error('Unreachable') + } + catch (e) { + expect((e as Error).message).toMatch('should fail!') + expect((e as Error).cause).toEqual(true) + } }); test('unwrap', () => { - expect(() => { + try { const err = Err({ message: 'bad error' }).unwrap(); expect_never(err, true); - }).toThrowError('{"message":"bad error"}'); + throw new Error('Unreachable') + } + catch (e) { + expect((e as Error).message).toMatch('{"message":"bad error"}') + expect((e as Error).cause).toEqual({ message: 'bad error' }) + } }); test('map', () => {