Skip to content

Commit

Permalink
Added improved typings for Array.every
Browse files Browse the repository at this point in the history
  • Loading branch information
feathecutie committed Dec 19, 2023
1 parent b2df073 commit 2f5a0bd
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 0 deletions.
5 changes: 5 additions & 0 deletions package.json
Expand Up @@ -83,6 +83,11 @@
"types": "./dist/storage.d.ts",
"import": "./dist/storage.mjs",
"default": "./dist/storage.js"
},
"./every-boolean": {
"types": "./dist/every-boolean.d.ts",
"import": "./dist/every-boolean.mjs",
"default": "./dist/every-boolean.js"
}
},
"keywords": [],
Expand Down
23 changes: 23 additions & 0 deletions src/entrypoints/every-boolean.d.ts
@@ -0,0 +1,23 @@
/// <reference path="utils.d.ts" />

interface Array<T> {
every<U>(
predicate: BooleanConstructor,
thisArg?: any,
): this is this extends U[]
? TSReset.NonFalsy<T>[]
: this[number] extends TSReset.NonFalsy<T>
? this
: never;
}

interface ReadonlyArray<T> {
every<U>(
predicate: BooleanConstructor,
thisArg?: any,
): this is this extends U[]
? TSReset.NonFalsy<T>[]
: this[number] extends TSReset.NonFalsy<T>
? this
: never;
}
72 changes: 72 additions & 0 deletions src/tests/every-boolean.ts
@@ -0,0 +1,72 @@
import { doNotExecute, Equal, Expect } from "./utils";

doNotExecute(() => {
const arr = [1, 2, 3, undefined];

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, number[]>>];
} else {
type tests = [Expect<Equal<typeof arr, (number | undefined)[]>>];
}
});

doNotExecute(() => {
const arr = [1, 2, 3, "four"];

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, (number | string)[]>>];
} else {
type tests = [Expect<Equal<typeof arr, never>>];
}
});

doNotExecute(() => {
const arr = ["1", "2"] as const;

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, readonly ["1", "2"]>>];
} else {
type tests = [Expect<Equal<typeof arr, never>>];
}
});

doNotExecute(() => {
const arr = ["1", "2", undefined] as const;

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, never>>];
} else {
type tests = [Expect<Equal<typeof arr, readonly ["1", "2", undefined]>>];
}
});

doNotExecute(() => {
const arr = [0, null, undefined, false, ""] as const;

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, never>>];
} else {
type tests = [
Expect<Equal<typeof arr, readonly [0, null, undefined, false, ""]>>,
];
}
});

doNotExecute(() => {
const arr: (0 | null | undefined | false | "" | 0n)[] = [
0,
null,
undefined,
false,
"",
0n,
];

if (arr.every(Boolean)) {
type tests = [Expect<Equal<typeof arr, never[]>>];
} else {
type tests = [
Expect<Equal<typeof arr, (0 | null | undefined | false | "" | 0n)[]>>,
];
}
});

0 comments on commit 2f5a0bd

Please sign in to comment.