Skip to content

Commit

Permalink
fix: split error declarations and fix implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
JanMalch committed Oct 30, 2020
1 parent c4ceaf3 commit e0daabb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ describe('utils', () => {
new PreconditionError('Failed!')
);
});
it('should error with the given message', () => {
expect(() => error('Failed!')).toThrowError(
new AssertionError('Failed!')
);
});
});

describe('NonNullish contract tests', () => {
Expand Down
25 changes: 23 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,20 @@ export function isDefined<T>(value: T): value is NonNullable<T> {

/* eslint-disable @typescript-eslint/no-explicit-any, new-cap */

/**
* Always throws an `AssertionError` with the given message.
* It can come in handy when assigning values with a ternary operator or the null operators.
* @param message the message for the `AssertionError`
* @see AssertionError
* @example
* function myFun(foo: string | null) {
* const bar = foo ?? error(PreconditionError, 'Argument may not be null');
* const result = bar.length > 0 ? 'OK' : error('Something went wrong!');
* }
*/
export function error(
message?: string
): never;
/**
* Always throws an error of the given type with the given message.
* It can come in handy when assigning values with a ternary operator or the null operators.
Expand All @@ -211,10 +225,17 @@ export function isDefined<T>(value: T): value is NonNullable<T> {
* }
*/
export function error(
errorType: new (...args: any[]) => Error = AssertionError,
errorType?: new (...args: any[]) => Error,
message?: string
): never;

export function error(
errorType: string | (new (...args: any[]) => Error) = AssertionError,
message?: string
): never {
throw new errorType(message);
throw typeof errorType === 'string'
? new AssertionError(errorType)
: new errorType(message);
}

/* eslint-enable @typescript-eslint/no-explicit-any, new-cap */
Expand Down

0 comments on commit e0daabb

Please sign in to comment.