isBoolean()

isBoolean()

Checks if any value is a boolean type, or the obtained type from its object class equal to 'boolean', or an object type and an instance of Boolean that is equal to true or false.

is-boolean.func.ts
const isBoolean = <
  Type extends AnyBoolean = boolean,
  Payload extends object = object
>(
  value: any,
  callback: ResultCallback<any, Payload> = resultCallback,
  payload?: Payload
): value is Type =>
  callback(
    (typeof value === 'boolean' ||
    typeOf(value) === 'boolean' ||
    (typeof value === 'object' && value instanceof Boolean)) &&
    (value.valueOf() === true || value.valueOf() === false),
    value,
    payload
  );

Generic type variables

TypeextendsAnyBoolean=boolean

The Type generic type variable constrained by generic type AnyBoolean by default of boolean indicates the type of the given value via the return type.

Payloadextendsobject=object

Parameters

value: any

The value of any type to check.

callback: ResultCallback<any, Payload>

payload?: Payload

Return type

value is Type

The return type is a boolean as the result of its statement, indicating the value is a generic type variable Type constrained by AnyBoolean by default equal to the boolean.

Returns

The return value is a boolean indicating whether the provided value is a boolean type or an instance of Boolean.

Example usage

Basic example

// Basic example usage.
import { isBoolean } from '@angular-package/type';

isBoolean(false); // Returns `true` as `value is boolean`
isBoolean(new Boolean(false)); // Returns `true` as `value is boolean`

Parameters callback and payload

// Callback and payload parameters example usage.
import { isBoolean } from '@angular-package/type';

isBoolean('my name', (result, value, payload) => {
  if (result === false) {
    value // "my name"
    if (payload) {
      // Change the result from `false` to `true`.
      if (payload === payload.accepted) {
        result = true;
      }
    }
  }
  return result;
}, { accepted: 'my name' }); // Returns `true` as `value is boolean`.

String as boolean

// String as boolean example usage.
import { isBoolean } from '@angular-package/type';

const fakeBoolean = new String('');

Object.assign(fakeBoolean, {
  get [Symbol.toStringTag](): string {
    return 'boolean';
  },
});

isBoolean(fakeBoolean); // false
typeOf(fakeBoolean); // "boolean"
typeof fakeBoolean; // "object"

Boolean as string

// Boolean as string example.
import { isBoolean } from '@angular-package/type';

const stringAsBoolean = new Boolean('');

Object.assign(stringAsBoolean, {
  get [Symbol.toStringTag](): string {
    return 'string';
  },
});

isBoolean(stringAsBoolean); // true
typeOf(stringAsBoolean); // "string"
typeof stringAsBoolean; // "object"

Last updated

Was this helpful?