From 44d3fb008d30b638402819fa73d9bc9efb5070c9 Mon Sep 17 00:00:00 2001 From: JanMalch <25508038+JanMalch@users.noreply.github.com> Date: Fri, 30 Oct 2020 12:48:13 +0100 Subject: [PATCH] feat: add optional message to unreachable --- README.md | 6 +++++- index.test.ts | 8 +++++++- index.ts | 8 ++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 70256bc..f132f5b 100644 --- a/README.md +++ b/README.md @@ -209,10 +209,14 @@ Asserts that a code branch is unreachable. If it is, the compiler will throw a t If this function is reached at runtime, an error will be thrown. ```ts -function unreachable(value: never): never; +function unreachable( + value: never, + message = 'Reached an unreachable case' +): never; ``` - `value` - a value +- `message` - an optional message for the error **Example:** diff --git a/index.test.ts b/index.test.ts index 75bc233..5dbf0b1 100644 --- a/index.test.ts +++ b/index.test.ts @@ -122,7 +122,13 @@ describe('unreachable', () => { 'Reached an unreachable case' ); }); - + it('should always throw an error at runtime with the given message', () => { + expectError( + () => unreachable(true as never, 'Test'), + AssertionError, + 'Test' + ); + }); it('should not throw an error when the switch is exhaustive', () => { enum MyEnum { A, diff --git a/index.ts b/index.ts index e237155..2509830 100644 --- a/index.ts +++ b/index.ts @@ -256,6 +256,7 @@ export function error( * Asserts that a code branch is unreachable. If it is, the compiler will throw a type error. * If this function is reached at runtime, an error will be thrown. * @param value a value + * @param message an optional message for the error * @throws AssertionError in any case * @example * function myFun(foo: MyEnum): string { @@ -267,6 +268,9 @@ export function error( * } * } */ -export function unreachable(value: never): never { - throw new AssertionError('Reached an unreachable case'); +export function unreachable( + value: never, + message = 'Reached an unreachable case' +): never { + throw new AssertionError(message); }