js-draw
Version:
Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.
76 lines (75 loc) • 2.19 kB
JavaScript
// Note: Arrow functions cannot be used for type assertions. See
// https://github.com/microsoft/TypeScript/issues/34523
/**
* Compile-time assertion that a branch of code is unreachable.
* @internal
*/
export function assertUnreachable(key) {
// See https://stackoverflow.com/a/39419171/17055750
throw new Error(`Should be unreachable. Key: ${key}.`);
}
/**
* Throws an exception if the typeof given value is not a number or `value` is NaN.
*
* @example
* ```ts
* const foo: unknown = 3;
* assertIsNumber(foo);
*
* assertIsNumber('hello, world'); // throws an Error.
* ```
*/
export function assertIsNumber(value, allowNaN = false) {
if (typeof value !== 'number' || (!allowNaN && isNaN(value))) {
throw new Error('Given value is not a number');
}
}
/** Throws an `Error` if the given `value` is not a `string`. */
export function assertIsString(value) {
if (typeof value !== 'string') {
throw new Error('Given value is not a string');
}
}
export function assertIsArray(values) {
if (!Array.isArray(values)) {
throw new Error('Asserting isArray: Given entity is not an array');
}
}
/**
* Throws if any of `values` is not of type number.
*/
export function assertIsNumberArray(values, allowNaN = false) {
assertIsArray(values);
assertIsNumber(values.length);
for (const value of values) {
assertIsNumber(value, allowNaN);
}
}
/**
* Throws if any of `values` is not of type `string`.
*/
export function assertIsStringArray(values) {
assertIsArray(values);
assertIsNumber(values.length);
for (const value of values) {
assertIsString(value);
}
}
/**
* Throws an exception if `typeof value` is not a boolean.
*/
export function assertIsBoolean(value) {
if (typeof value !== 'boolean') {
throw new Error('Given value is not a boolean');
}
}
export function assertTruthy(value) {
if (!value) {
throw new Error(`${JSON.stringify(value)} is not truthy`);
}
}
export function assertIsObject(value) {
if (typeof value !== 'object') {
throw new Error(`AssertIsObject: Given entity is not an object (type = ${typeof value})`);
}
}