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

181
Vistas
What is the good practice way of checking if an object is equal to a certain type?
typeof true === "boolean"

To me, the above line of code is prone to bugs because the string "boolean" can easily be misspelled:

typeof true === "Boolean"

So there has to be a better, built-in, function to do this.

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

0

You could compare with typeof true.

if(typeof someVar === typeof true){

}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I suppose you could compare against the two possible values:

if (someVal === true || someVal === false)

which will throw a ReferenceError if you've misspelled one of them - but other than that, JavaScript doesn't really have the sort of strict-ness you're looking for.

This is one of the situations in which I'd highly recommend TypeScript, which will indeed warn you against doing such a thing (and will also warn you against many other type-related errors that are easy to make):

const someBool = Math.random() < 0.5 ? '123' : true;
if (typeof someBool === 'boolea') {
    
}

throws

This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"boolea"' have no overlap.

enter image description here

I consider TypeScript to be essential for any reasonable-sized script because of the many possible mistakes it guards against - it can turn annoying or hard-to-debug runtime errors into trivially fixable compile-time errors.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I use this snippet in my code

// Type checker function
const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());

// Tests
console.log(isType("array", []));
console.log(isType("object", {}));
console.log(isType("regexp", new RegExp("foobar")));
console.log(isType("BOOlean", false));

// Last is false
console.log(isType("string", []));

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