check-is-truthy
TypeScript icon, indicating that this package has built-in type declarations

0.0.6 • Public • Published

check-is-truthy

Utilities and types to help with simple Boolean checks

This is intended to be used with TypeScript, but it should work with JavaScript as well.

This package is side-effect free and can be fully tree-shaken.

Installation

npm install check-is-truthy

or

yarn add check-is-truthy

Why is this useful?

By and large, the primary useful thing about this package is the isTruthy function which can be used within standard JavaScript functions like Array.prototype.filter or within other utilities which take a predicate function with a type guard, such as Lodash's _.find.

Though the same behavior can be achieved at runtime by calling the Boolean constructor as a function, TypeScript makes no special handling of this with regards to type guards as mentioned above.

isTruthy

isTruthy is a function that takes a value and returns a boolean indicating whether it is "truthy" within JavaScript.

It is particularly useful for filtering collections, and can be used in most cases where predicates are used, such as Array.prototype.filter.

import { isTruthy } from "check-is-truthy";

doSomethingComplex(["foo", "bar", doSomething && expensive()].filter(isTruthy));

isFalsy

isFalsy is a function that takes a value and returns a boolean indicating whether it is "falsy" within JavaScript.

toggle

toggle is a function that takes a value and returns its logical opposite. This has the effect of cycling between true and false.

function MyComponent() {
  const [isOpen, setIsOpen] = useState(false);
  const toggleIsOpen = useCallback(() => setIsOpen(toggle), []);
  return (
    <Modal isOpen={isOpen}>
      <button onClick={toggleIsOpen} />
    </Modal>
  );
}

type FalsyValue

FalsyValue is a type that represents all values that are falsy in JavaScript.

One can use TypeScript's built-in Extract or Exclude types to extract values from a type that are falsy (or truthy).

import type { FalsyValue } from "check-is-truthy";

function doSomething<T>(
  value: T,
  whenTruthy: (value: Exclude<T, FalsyValue>) => void,
  whenFalsy: (value: Extract<T, FalsyValue>) => void
) {
  if (value) {
    // in this branch, we know `value` is truthy
    whenTruthy(value);
  } else {
    // in this branch, we know `value` is falsy
    whenFalsy(value);
  }
}

NaN

The reserved value NaN. This is equivalent to the global NaN value.

This has a special type of NaN, which is an opaque value that can represent NaN.

It is not fully safe to use, as NaN values can be easily created through other means that are not typed as NaN.

isNaN

Equivalent to Number.isNaN.

This is provided as a convenience as a check for the NaN value as the NaN type.

Package Sidebar

Install

npm i check-is-truthy

Weekly Downloads

1

Version

0.0.6

License

MIT

Unpacked Size

11.6 kB

Total Files

6

Last publish

Collaborators

  • ckknight