Cómo comprobar si el tipo es booleano


¿Cómo puedo comprobar si el tipo de una variable es de tipo booleano?

Quiero decir, hay algunas alternativas como:

if(jQuery.type(new Boolean()) === jQuery.type(variable))
      //Do something..

Pero eso no me parece bonito.

¿Hay una manera más limpia de lograr esto?

Author: Matias Cicero, 2015-03-02

12 answers

Eso es lo que typeof está ahí para. Los paréntesis son opcionales ya que es un operador .

if(typeof(variable) === "boolean"){
  // variable is a boolean
}

Una forma segura para el futuro sería comparar con un valor booleano conocido que es, true o false, gracias a @MarcusJuniusBrutus.

if(typeof(variable) == typeof(true)){
  // variable is a boolean
}
 295
Author: Amit Joki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-04 14:10:16

Si solo desea verificar un valor primitivo

typeof variable === 'boolean'

Si por alguna extraña razón tiene booleanos creados con el constructor, esos no son realmente booleanos sino objetos que contienen un valor booleano primitivo, y una forma de verificar tanto los booleanos primitivos como los objetos creados con new Boolean es hacer:

function checkBool(bool) {
    return typeof bool === 'boolean' || 
           (typeof bool === 'object' && 
            bool !== null            &&
           typeof bool.valueOf() === 'boolean');
}

function checkBool(bool) {
    return typeof bool === 'boolean' || 
           (typeof bool === 'object' && 
            bool !== null            &&
           typeof bool.valueOf() === 'boolean');
}

console.log( checkBool( 'string'          )); // false, string
console.log( checkBool( {test: 'this'}    )); // false, object
console.log( checkBool( null              )); // false, null
console.log( checkBool( undefined         )); // false, undefined
console.log( checkBool( new Boolean(true) )); // true
console.log( checkBool( new Boolean()     )); // true
console.log( checkBool( true              )); // true
console.log( checkBool( false             )); // true
 27
Author: adeneo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-26 15:06:29

Puedes usar Javascript puro para lograr esto:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');
 14
Author: Morry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-02 16:27:17

Con JavaScript puro , simplemente haga esto:

function isBoolean(val) {
   return val === false || val === true;
}

O una línea ES6 camino ...

const isBoolean = val => 'boolean' === typeof val;

Y llámalo!

isBoolean(false); //return true

También en Underscore código fuente lo comprueban así(con el _. al inicio del nombre de la función):

isBoolean = function(obj) {
   return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};

También en jQuery puedes comprobarlo así:

jQuery.type(true); //return "boolean"

En React , si usa PropTypes, puede verificar que un valor sea booleano como este:

MyComponent.propTypes = {
  children: PropTypes.bool.isRequired
};

También otro manera de hacerlo, es como convertir el valor a booleano y ver si es exactamente el mismo todavía, algo así como:

const isBoolean = val => !!val === val;

O como:

const isBoolean = val => Boolean(val) === val;

Y llámalo!

isBoolean(false); //return true

Se recomienda no usar ningún framework para esto, ya que es realmente un simple check en JavaScript.

 13
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-13 02:23:12

Hay tres formas "vainilla" de verificar esto con o sin jQuery.

  1. Primero, y probablemente el más óptimo, es forzar la evaluación booleana por coerción, luego verificar si es igual al valor original:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  2. Haciendo una simple typeof comprobación:

    function isBoolean( n ) {
        return typeof n === 'boolean';
    }
    
  3. Haciendo una instanciación completamente excesiva e innecesaria de una envoltura de clase en una primativa:

    function isBoolean( n ) {
        return n instanceof Boolean;
    }
    

El tercero solo regresará true si crea una clase new Boolean y la pasa.

Para elaborar sobre la coerción primitivas (como se muestra en #1), todos los tipos primitivos se pueden verificar de esta manera:

  • Boolean:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  • Number:

    function isNumber( n ) {
        return +n === n;
    }
    
  • String:

    function isString( n ) {
        return ''+n === n;
    }
    
 11
Author: iSkore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-02 11:52:44

Si desea que su función también pueda validar objetos booleanos, la solución más eficiente debe ser:

function isBoolean(val) {
  return val === false || val === true || val instanceof Boolean;
}
 3
Author: Willem Franco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-04 13:53:13

La forma más confiable de verificar el tipo de una variable en JavaScript es la siguiente :

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"

La razón de esta complicación es que typeof true devuelve "boolean" while typeof new Boolean(true) devuelve "object".

 2
Author: Volodymyr Frolov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-02 16:33:43

Yo iría con Lodash: isBoolean comprueba si la variable passed-in es un objeto booleano primitivo o un objeto contenedor booleano y así da cuenta de todos los casos.

 2
Author: Marcus Junius Brutus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-08 16:57:06

Puede crear una función que compruebe el typeof para un argumento.

function isBoolean(value) {
  return typeof value === "boolean";
}
 0
Author: Mohsen Kadoura,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-13 19:20:48

A veces necesitamos una sola forma de comprobarlo. typeof no funciona para la fecha, etc. Así que lo hice fácil por

Date.prototype.getType() { return "date"; }

También para Number, String, Boolean etc. a menudo tenemos que comprobar el tipo de una sola manera...

 0
Author: Imam Kuncoro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-30 06:52:07

Crear funciones como isBoolean que contiene oneliner typeof v === "boolean" parece muy poco práctico a largo plazo. me sorprende que casi todo el mundo sugiera crear su propia función. Parece ser el mismo cáncer que extender prototipos nativos.

  • necesitas recrearlos en cada proyecto en el que estés involucrado
  • otros desarrolladores pueden tener diferentes hábitos,, o la necesidad de comprobar la fuente de su función para ver qué impementation de comprobar que utiliza, para saber cuáles son los puntos débiles de su comprobar
  • se verá fruustrado cuando intente escribir un liner en la consola en el sitio que no pertenezca a su proyecto

Solo recuerda typeof v === "boolean" y eso es todo. Añade una plantilla a tu IDE para poder ponerla por unos atajos de tres letras y ser feliz.

 0
Author: Kamil Orzechowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-14 13:31:54
if(['true', 'yes', '1'].includes(single_value)) {
    return  true;   
}
else if(['false', 'no', '0'].includes(single_value)) {
    return  false;  
}

Si tienes una cadena

 0
Author: Denver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 10:01:33