Skip to content

Commit

Permalink
Add arrayIncludes() (#8)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
ifiokjr and sindresorhus authored Nov 3, 2021
1 parent 066ec01 commit f988c40
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
24 changes: 24 additions & 0 deletions source/array-includes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
An alternative to `Array.prototype.includes` that properly acts as a type guard.
It was [rejected](https://github.com/microsoft/TypeScript/issues/26255#issuecomment-748211891) from being done in TypeScript itself.
@example
```
import {arrayIncludes} from 'ts-extras';
const values = ['a', 'b', 'c'] as const;
const valueToCheck: unknown = 'a';
if (arrayIncludes(values, valueToCheck)) {
// We now know that the value is of type `typeof values[number]`.
}
```
*/
export function arrayIncludes<Type>(
array: Type[] | readonly Type[],
item: unknown,
fromIndex?: number,
): item is Type {
return array.includes(item as Type, fromIndex);
}
1 change: 1 addition & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {arrayIncludes} from './array-includes.js';
export {isDefined} from './is-defined.js';
export {isEmpty} from './is-empty.js';
export {assertError} from './assert-error.js';
Expand Down
29 changes: 29 additions & 0 deletions test/array-includes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import test from 'ava';
import {arrayIncludes} from '../source/index.js';

test('arrayIncludes()', t => {
const values = ['a', 'b', 'c'] as const;
const validValue: unknown = 'a';
const invalidValue: unknown = 'd';
let testValueType: typeof values[number];

t.true(arrayIncludes(values, validValue));
t.false(arrayIncludes(values, invalidValue));

if (arrayIncludes(values, validValue)) {
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
values.push(); // Ensure readonly array is still readonly.

testValueType = validValue;
} else {
// @ts-expect-error
testValueType = validValue;

// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
values.push(); // Ensure readonly array is still readonly.
}

t.is(testValueType, 'a');
});

0 comments on commit f988c40

Please sign in to comment.