From 8719c5f930b55b33c93dd8e21592938935afec2f Mon Sep 17 00:00:00 2001 From: Alex Regan Date: Tue, 13 Feb 2018 04:22:25 -0700 Subject: [PATCH] feat(result): `expect` impl --- src/result.class.ts | 9 +++++++++ src/result.test.ts | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/result.class.ts b/src/result.class.ts index 9c79ac9..dd2584b 100644 --- a/src/result.class.ts +++ b/src/result.class.ts @@ -184,6 +184,15 @@ export class Result { }); } + public expect(err_msg: string): T { + return this.match({ + ok: (t: T) => t, + err: (_: E) => { + throw new Error(err_msg); + }, + }); + } + public static Ok(val: T): Result { return new Result(Ok(val)); } diff --git a/src/result.test.ts b/src/result.test.ts index 7555a9b..f46644d 100644 --- a/src/result.test.ts +++ b/src/result.test.ts @@ -226,3 +226,13 @@ describe("Result.unwrap", async () => { expect(() => Err("error").unwrap()).toThrow(Error); }); }); + +describe("Result.expect", async () => { + it("should not throw with Ok", async () => { + expect(Ok(2).expect("my error")).toBe(2); + }); + + it("should throw with Err", async () => { + expect(() => Err("error").expect("my error")).toThrow("my error"); + }); +});