Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

0

You could compare with typeof true.

if(typeof someVar === typeof true){

}
about 4 years ago · Juan Pablo Isaza Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda