Skip to content
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
4 changes: 3 additions & 1 deletion src/typeChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,10 @@ export const isArrayOf: <const T>(
const k = `isArrayOf${typeName}`;
return {
typeGuard: {
// findIndex() visits holes as undefined, matching the diagnosis
// path; every() would skip them.
[k]: (v: unknown): v is Array<T> =>
Array.isArray(v) && v.every((i) => isT(i)),
Array.isArray(v) && v.findIndex((i) => !isT(i)) < 0,
}[k],
*serialize(depth, done) {
yield "Array<";
Expand Down
38 changes: 37 additions & 1 deletion src/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
isOptionalOf,
typeChecker,
} from "./typeChecker.ts";
import type { ValidationIssue } from "./types.ts";
import type { TypeChecker, ValidationIssue } from "./types.ts";
import { validate, validateAll } from "./validate.ts";
import {
ValidationIssueCode,
Expand Down Expand Up @@ -406,3 +406,39 @@ test("exact object validation preserves its input without sanitizing it", () =>
assert.deepEqual(Object.getOwnPropertyDescriptors(input), before);
assert.equal(Object.isFrozen(input), true);
});

const assertArrayResult = <T>(
checker: TypeChecker<Array<T>>,
input: unknown,
expected: boolean,
): void => {
const label = `${checker} ${JSON.stringify(input)}`;
assert.equal(checker(input), expected, label);
assert.equal(checker.test(input) === null, expected, label);
assert.equal(validate(input, checker).ok, expected, label);
assert.equal(validateAll(input, checker).ok, expected, label);
};

test("array holes are checked like undefined elements on every path", () => {
const isStrings = isArrayOf(isString);
const isOptionalStrings = isArrayOf(isOptionalOf(isString));
// biome-ignore lint/suspicious/noSparseArray: sparse arrays are the subject
const mixed = ["a", , "c"];
const cases: Array<[unknown, boolean, boolean]> = [
// [input, isStrings, isOptionalStrings]
[[], true, true],
[new Array(2), false, true],
[mixed, false, true],
[["a", undefined], false, true],
[["a", "b"], true, true],
];
for (const [input, strings, optionalStrings] of cases) {
assertArrayResult(isStrings, input, strings);
assertArrayResult(isOptionalStrings, input, optionalStrings);
}
const result = validate(mixed, isStrings);
assert.equal(result.ok, false);
if (!result.ok) {
assert.deepEqual(result.issue.path, [1]);
}
});
Loading