Skip to content

Commit

Permalink
Fix passing in assertion message to assertArray (#210)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
marlun78 and sindresorhus authored Sep 6, 2024
1 parent ab85d9b commit 5565c5e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 5 additions & 3 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1143,14 +1143,16 @@ export function assertAny(predicate: Predicate | Predicate[], ...values: unknown
}
}

export function assertArray<T = unknown>(value: unknown, assertion?: (element: unknown) => asserts element is T, message?: string): asserts value is T[] {
export function assertArray<T = unknown>(value: unknown, assertion?: (element: unknown, message?: string) => asserts element is T, message?: string): asserts value is T[] {
if (!isArray(value)) {
throw new TypeError(message ?? typeErrorMessage('Array', value));
}

if (assertion) {
// eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference
value.forEach(assertion);
for (const element of value) {
// @ts-expect-error: "Assertions require every name in the call target to be declared with an explicit type annotation."
assertion(element, message);
}
}
}

Expand Down
4 changes: 4 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,10 @@ test('is.array', t => {
x[0]?.toFixed(0);
}
});

t.throws(() => {
assert.array([1, '2'], assert.number, 'Expected numbers');
}, {message: /Expected numbers/});
});

test('is.function', t => {
Expand Down

0 comments on commit 5565c5e

Please sign in to comment.