Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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'));

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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) }

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda