How to check if type is Boolean

前端 未结 16 1796
深忆病人
深忆病人 2020-12-07 10:09

How can I check if a variable\'s type is of type Boolean?

I mean, there are some alternatives such as:

if(jQuery.type(new Boolean()) === jQuery.type(         


        
16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 10:33

    With pure JavaScript, you can just simply use typeof and do something like typeof false or typeof true and it will return "boolean"...

    But that's not the only way to do that, I'm creating functions below to show different ways you can check for Boolean in JavaScript, also different ways you can do it in some new frameworks, let's start with this one:

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

    Or one-line ES6 way ...

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

    and call it like!

    isBoolean(false); //return true
    

    Also in Underscore source code they check it like this(with the _. at the start of the function name):

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

    Also in jQuery you can check it like this:

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

    In React, if using propTypes, you can check a value to be boolean like this:

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

    If using TypeScript, you can use type boolean also:

    let isDone: boolean = false;
    

    Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:

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

    or like:

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

    and call it!

    isBoolean(false); //return true
    

    It's not recommended using any framework for this as it's really a simple check in JavaScript.

提交回复
热议问题