Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add is.TupleLike #189

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
"ts-node": "^10.9.1",
"typescript": "^5.0.4",
"xo": "^0.54.2",
"zen-observable": "^0.10.0"
"zen-observable": "^0.10.0",
"expect-type": "^0.16.0"
},
"sideEffects": false,
"ava": {
Expand Down
20 changes: 20 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,26 @@ function foo() {
foo();
```

##### .tupleLike(value, guards)

A `value` is tuple-like if it matches the provided `guards` array both in `.length` and in types.

```js
is.tupleLike([1], [is.number]);
//=> true
```

```js
function foo() {
const tuple = [1, '2', true];
if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) {
tuple // [number, string, boolean]
}
}

foo();
```

#### .positiveNumber(value)

Check if `value` is a number and is more than 0.
Expand Down
21 changes: 21 additions & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,24 @@ export type ArrayLike<T> = {
const isValidLength = (value: unknown): value is number => is.safeInteger(value) && value >= 0;
is.arrayLike = <T = unknown>(value: unknown): value is ArrayLike<T> => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength((value as ArrayLike<T>).length);

type TypeGuard<T> = (value: unknown) => value is T;

// eslint-disable-next-line @typescript-eslint/ban-types
type ResolveTypesOfTypeGuardsTuple<TypeGuardsOfT, ResultOfT extends unknown[] = [] > =
TypeGuardsOfT extends [TypeGuard<infer U>, ...infer TOthers]
? ResolveTypesOfTypeGuardsTuple<TOthers, [...ResultOfT, U]>
: TypeGuardsOfT extends undefined[]
? ResultOfT
: never;

is.tupleLike = <T extends Array<TypeGuard<unknown>>>(value: unknown, guards: [...T]): value is ResolveTypesOfTypeGuardsTuple<T> => {
if (is.array(guards) && is.array(value) && guards.length === value.length) {
return guards.every((guard, index) => guard(value[index]));
}

return false;
};

is.inRange = (value: number, range: number | number[]): value is number => {
if (is.number(range)) {
return value >= Math.min(0, range) && value <= Math.max(range, 0);
Expand Down Expand Up @@ -482,6 +500,7 @@ export const enum AssertionTypeDescription {
safeInteger = 'integer', // eslint-disable-line @typescript-eslint/no-duplicate-enum-values
plainObject = 'plain object',
arrayLike = 'array-like',
tupleLike = 'tuple-like',
typedArray = 'TypedArray',
domElement = 'HTMLElement',
nodeStream = 'Node.js Stream',
Expand Down Expand Up @@ -579,6 +598,7 @@ type Assert = {
plainObject: <Value = unknown>(value: unknown) => asserts value is Record<PropertyKey, Value>;
typedArray: (value: unknown) => asserts value is TypedArray;
arrayLike: <T = unknown>(value: unknown) => asserts value is ArrayLike<T>;
tupleLike: <T extends Array<TypeGuard<unknown>>>(value: unknown, guards: [...T]) => asserts value is ResolveTypesOfTypeGuardsTuple<T>;
domElement: (value: unknown) => asserts value is HTMLElement;
observable: (value: unknown) => asserts value is ObservableLike;
nodeStream: (value: unknown) => asserts value is NodeStream;
Expand Down Expand Up @@ -687,6 +707,7 @@ export const assert: Assert = {
plainObject: <Value = unknown>(value: unknown): asserts value is Record<PropertyKey, Value> => assertType(is.plainObject(value), AssertionTypeDescription.plainObject, value),
typedArray: (value: unknown): asserts value is TypedArray => assertType(is.typedArray(value), AssertionTypeDescription.typedArray, value),
arrayLike: <T = unknown>(value: unknown): asserts value is ArrayLike<T> => assertType(is.arrayLike(value), AssertionTypeDescription.arrayLike, value),
tupleLike: <T extends Array<TypeGuard<unknown>>>(value: unknown, guards: [...T]): asserts value is ResolveTypesOfTypeGuardsTuple<T> => assertType(is.tupleLike(value, guards), AssertionTypeDescription.tupleLike, value),
domElement: (value: unknown): asserts value is HTMLElement => assertType(is.domElement(value), AssertionTypeDescription.domElement, value),
observable: (value: unknown): asserts value is ObservableLike => assertType(is.observable(value), 'Observable', value),
nodeStream: (value: unknown): asserts value is NodeStream => assertType(is.nodeStream(value), AssertionTypeDescription.nodeStream, value),
Expand Down
76 changes: 76 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import test, {type ExecutionContext} from 'ava';
import {JSDOM} from 'jsdom';
import {Subject, Observable} from 'rxjs';
import {temporaryFile} from 'tempy';
import {expectTypeOf} from 'expect-type';
import ZenObservable from 'zen-observable';
import is, {
assert,
Expand Down Expand Up @@ -1445,6 +1446,81 @@ test('is.arrayLike', t => {
});
});

test('is.tupleLike', t => {
(function () {
t.false(is.tupleLike(arguments, [])); // eslint-disable-line prefer-rest-params
})();

t.true(is.tupleLike([], []));
t.true(is.tupleLike([1, '2', true, {}, [], undefined, null], [is.number, is.string, is.boolean, is.object, is.array, is.undefined, is.nullOrUndefined]));
t.false(is.tupleLike('unicorn', [is.string]));

t.false(is.tupleLike({}, []));
t.false(is.tupleLike(() => {}, [is.function_]));
t.false(is.tupleLike(new Map(), [is.map]));

(function () {
t.throws(function () {
assert.tupleLike(arguments, []); // eslint-disable-line prefer-rest-params
});
})();

t.notThrows(() => {
assert.tupleLike([], []);
});
t.throws(() => {
assert.tupleLike('unicorn', [is.string]);
});

t.throws(() => {
assert.tupleLike({}, [is.object]);
});
t.throws(() => {
assert.tupleLike(() => {}, [is.function_]);
});
t.throws(() => {
assert.tupleLike(new Map(), [is.map]);
});

{
const tuple = [[false, 'unicorn'], 'string', true];

if (is.tupleLike(tuple, [is.array, is.string, is.boolean])) {
if (is.tupleLike(tuple[0], [is.boolean, is.string])) { // eslint-disable-line unicorn/no-lonely-if
const value = tuple[0][1];
expectTypeOf(value).toEqualTypeOf<string>();
}
}
}

{
const tuple = [{isTest: true}, '1', true, null];

if (is.tupleLike(tuple, [is.nonEmptyObject, is.string, is.boolean, is.null_])) {
const value = tuple[0];
expectTypeOf(value).toEqualTypeOf<Record<string | number | symbol, unknown>>();
}
}

{
const tuple = [1, '1', true, null, undefined];

if (is.tupleLike(tuple, [is.number, is.string, is.boolean, is.undefined, is.null_])) {
const numericValue = tuple[0];
const stringValue = tuple[1];
const booleanValue = tuple[2];
const undefinedValue = tuple[3];
const nullValue = tuple[4];
expectTypeOf(numericValue).toEqualTypeOf<number>();
expectTypeOf(stringValue).toEqualTypeOf<string>();
expectTypeOf(booleanValue).toEqualTypeOf<boolean>();
expectTypeOf(undefinedValue).toEqualTypeOf<undefined>();
// eslint-disable-next-line @typescript-eslint/ban-types
expectTypeOf(nullValue).toEqualTypeOf<null>();
}
}
});

test('is.inRange', t => {
const x = 3;

Expand Down