Skip to main content

contains

A utility function that determines whether a specific element is included in the array passed as the first argument.

includes throws a type error when checking if an element with an incompatible type is included when using as const. This function improves that behavior using the some method.

typescript
const test = (value: number) => {
const arr = [1, 2, 3, 4] as const;
arr.includes(value); // Argument of type 'number' is not assignable to parameter of type '1 | 2 | 3 | 4'.
};

When checking whether an element is included via the some method, Object.is is used by default. If needed, a comparator function can be provided as the third argument.

Object.is is used because it is stricter than == and produces results closer to developer expectations compared to ===. For example, unlike ===, it considers NaN equal to itself and treats -0 and +0 as different values.

typescript
-0 === +0; // true
Object.is(-0, +0); // false

NaN === NaN; // false;
Object.is(NaN, NaN); // true
Object.is(NaN, 0 / 0); // true

Code

🔗 View source code


Interface

typescript
function contains<T>(
arr: T[] | readonly T[],
value: unknown,
comparator?: (x: any, y: any) => boolean
): value is T;

Usage

Basic Usage

typescript
import { contains } from '@modern-kit/utils';

const arr = [0, 1, 2, 3, NaN, {}];

contains(arr, 1); // true
contains(arr, NaN); // true

contains(arr, -0); // false
contains(arr, 4); // false
contains(arr, '3'); // false
contains(arr, {}); // false

Comparator Usage

typescript
const arr = [{ a: 1, b: 2 }];

contains(arr, { a: 1, c: 2 }, (x, y) => x.a === y.a); // true
contains(
arr,
{ a: 1, b: 2 },
(x, y) => JSON.stringify(x) === JSON.stringify(y)
); // true

Narrowing types Usage

typescript
const arr = [2, 3, 'foo'] as const;
const value = 'foo' as unknown;

if (contains(arr, value)) {
value; // 2 | 3 | 'foo'
} else {
value; // unknown
}

References