'Most idiomatic way to do validation on type

I am used to using something like the following pattern on a dynamic language to check/assert type:

function square(num) {
    // pretend we don't already have a TypeError
    if (!num instanceof Number) throw new MyCustomError("Only a number is allowed here") 
    return num * num;
}

However, js doesn't allow instanceof on primitives, well, at least in a way that helps check the type easily such as I'd want in the above. What is the recommended/idiomatic way to do this, just compare to a string? Such as:

// create our own error
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

function square(num) {
  // pretend we don't want a TypeError
  if (typeof num != 'number')
    throw new ValidationError("Only a number is allowed here") 
  return num * num;
}

console.log(square(2));
console.log(square('abc'));


Solution 1:[1]

Instead of checking if a variable is not a Number by doing an instanceof check (which does not work on primitives), try the following.

const num = 78;
console.log(isNaN(num) || typeof num !== "number");

In here, we are using the typeof keyword, as it is supported by JavaScript primitives. We are also checking if the value is NaN.

Solution 2:[2]

Create a reusable decorator function that makes any function which only accepts numeric parameters throw an error if called with non-numeric arguments:

function multiply(a, b) { return a * b }

function numArgsOnly(fn) {
  return function(...args) {
    if (args.some(n => n!==Number(n))) 
      throw `${args.find(n => n!==Number(n))} is not a number`;
    return fn(...args);
  }
}

const safeMultiply = numArgsOnly(multiply);

console.log(safeMultiply(3,9));

try {
  safeMultiply(3,'foo');
} catch (e) { console.error(e) }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2