Skip to content

Commit

Permalink
feat: add optional message to unreachable
Browse files Browse the repository at this point in the history
  • Loading branch information
JanMalch committed Oct 30, 2020
1 parent 9305ebf commit 44d3fb0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**

Expand Down
8 changes: 7 additions & 1 deletion index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 6 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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);
}

0 comments on commit 44d3fb0

Please sign in to comment.