Assert JS value or die trying

Make sure the JS value passed in is defined. Otherwise throw an error

by Eugene Trounev

HTML

<h1>
Check the console <kbd>[F12]</kbd>!
</h1>
<pre>
<code>
  function Assert(target: any, options: Object): void;
</code>
Insure the target has a value
or throw error if it does not
@export
@param {*} target value to be tested
@param {(IAssertOptions | string)} options test options, or error message string to be thrown
interface IAssertOptions {
   error: string; - error message string to be thrown
   failEmptyString: Boolean; - failt when value is an empty string ("")
   failNullValue: Boolean; - fail when value is null
   failZeroValue: Boolean; - fail when vaule is a zero (0)
   test: (target: any) => Boolean; - custom test to run (test must return true ONLY when value contains an error)
}
@returns {*} target
@example
<code>
const test = null;
Assert(test, "test value can not be Null!");
</code>
... will throw console error:
test value can not be Null!
</pre>

TypeScript

const defaultOptions = {
    error: "ReferenceError: test is not defined",
    failEmptyString: true,
    failNullValue: true,
    failZeroValue: false,
    test: null
};

/**
 * Insure the target has a value
 * or throw error if it does not
 * @export
 * @param {*} target value to be tested
 * @param {(IAssertOptions | string)} options test options, or error message string to be thrown
 * interface IAssertOptions {
 *    error: string; - error message string to be thrown
 *    failEmptyString: Boolean; - failt when value is an empty string ("")
 *    failNullValue: Boolean; - fail when value is null
 *    failZeroValue: Boolean; - fail when vaule is a zero (0)
 *    test: (target: any) => Boolean; - custom test to run (test must return true ONLY when value contains an error)
 * }
 * @example
 * const test = null;
 * Assert(test, "test value can not be Null!");
 * ... will throw console error:
 * test value can not be Null!
 */
function Assert(target, options) {
    let _opts: IAssertOptions = {} as IAssertOptions;
    Object.assign(
      _opts,
      defaultOptions,
      typeof options === "string" ? {error: options} : options
     );
    if (
        target === undefined ||
        _opts.failNullValue && target === null ||
        _opts.failZeroValue && target === 0 ||
        _opts.failEmptyString && target === "" ||
        _opts.test && _opts.test(target)
    ) throw _opts.error;
    return target;
}

const test = null;
Assert(test, "variable 'test' can NOT be null!");

/* const test2 = undefined; */
Assert(test2, "variable 'test2' is undefined!");

const test3 = "";
Assert(test3, "variable 'test3' can not be an empty string!");