isBoolean
The isBoolean utility is a type guard that checks if a given value is a boolean primitive (true or false).
Implementation
View Source Code
ts
/**
* Checks if the value is a boolean.
*
* @example
* ```ts
* isBoolean(true); // true
* isBoolean(false); // true
* isBoolean(123); // false
* isBoolean('hello world'); // false
* isBoolean({}); // false
* isBoolean([]); // false
* isBoolean(new Date()); // false
* isBoolean(null); // false
* isBoolean(undefined); // false
* isBoolean(NaN); // false
* ```
*
* @param arg - The argument to be checked.
*
* @returns `true` if the value is a boolean, else `false`.
*/
export function isBoolean(arg: unknown): arg is boolean {
return typeof arg === 'boolean';
}Features
- Isomorphic: Works in both Browser and Node.js.
- Type Guard: Automatically narrows types to
booleanwithin conditional blocks. - Strict Check: Only returns
truefor actual boolean primitives.
API
ts
function isBoolean(value: unknown): value is boolean;Parameters
value: The value to check.
Returns
trueif the value is a boolean; otherwise,false.
Examples
Basic Usage
ts
import { isBoolean } from '@vielzeug/toolkit';
isBoolean(true); // true
isBoolean(false); // true
isBoolean(1); // false
isBoolean('true'); // falseType Guarding
ts
import { isBoolean } from '@vielzeug/toolkit';
function process(val: unknown) {
if (isBoolean(val)) {
// val is narrowed to boolean
return val ? 'Yes' : 'No';
}
}Implementation Notes
- Returns
trueiftypeof value === 'boolean'. - Throws nothing; safe for any input type.