Skip to content

Commit e3d9cc8

Browse files
author
andy.patterson
committed
feat: array builder should take a singular specifier
Because arrays by default are of only one thing, we should only take a single `Validator` to specify the type. If we want an array of multiple types, then we should pass in a `Union`. An array that cares about the order of the different types is a tuple, we should consider adding `tuple` as a potential builder. BREAKING CHANGE: The contract for `v.array` has changed from taking an array of `Validator`s to taking a single `Validator`.
1 parent f316678 commit e3d9cc8

File tree

3 files changed

+13
-15
lines changed

3 files changed

+13
-15
lines changed

src/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,8 @@ export function partial<T extends Record<string, any>>(v: Validator<T>): Validat
232232
});
233233
}
234234

235-
export function array<V extends Validator<any>>(v: V[]) {
236-
return new Validator<Array<ValidType<V>>>({
235+
export function array<T>(v: Validator<T>) {
236+
return new Validator<T[]>({
237237
type: 'array',
238238
items: v.map(x => x.getSchema()),
239239
additionalItems: true,

tests/integration/api.test.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,16 @@ test('Generates correct type for validated object', () => {
6565

6666
test('Validates a deep object', () => {
6767
const validator = v.object({
68-
arr: v.array([
69-
v.number(),
70-
v.object({
71-
o: v.object({
72-
a: v.number(),
68+
arr: v.array(
69+
v.union([
70+
v.number(),
71+
v.object({
72+
o: v.object({
73+
a: v.number(),
74+
}),
7375
}),
74-
}),
75-
]),
76+
]),
77+
),
7678
});
7779

7880
const x: any = {

tests/unit/array.test.ts

+2-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { fail, pass, assertTypesEqual } from '../helpers/assert';
44
test('Can validate an array', () => {
55
const x: any = [21, 22, 23];
66

7-
const validator = v.array([ v.number() ]);
7+
const validator = v.array(v.number());
88

99
if (validator.isValid(x)) {
1010
assertTypesEqual<typeof x, number[]>();
@@ -21,11 +21,7 @@ test('Can validate a deep array', () => {
2121
[7, 8, 9],
2222
];
2323

24-
const validator = v.array([
25-
v.array([
26-
v.number(),
27-
]),
28-
]);
24+
const validator = v.array(v.array(v.number()));
2925

3026
if (validator.isValid(x)) {
3127
assertTypesEqual<typeof x, number[][]>();

0 commit comments

Comments
 (0)