Skip to content

Commit

Permalink
feat(validator): implement array validator
Browse files Browse the repository at this point in the history
  • Loading branch information
NWYLZW committed Mar 4, 2024
1 parent e37eeba commit bb5ad0a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
9 changes: 8 additions & 1 deletion packages/validator/src/types/structural.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function arrayValidator(t: typeof tn) {
return false
}
// distribute array and tuple
if ('length' in this) {
if (Object.hasOwnProperty.call(this, 'length')) {
// tuple
if (input.length !== this.shape.length) {
return false
Expand All @@ -51,6 +51,13 @@ export function arrayValidator(t: typeof tn) {
}
} else {
// array
const shapeItem = this.shape[0]
for (let i = 0; i < input.length; i++) {
const inputItem = input[i]
if (!shapeItem.test(inputItem)) {
return false
}
}
}
return true
},
Expand Down
21 changes: 20 additions & 1 deletion packages/validator/tests/types/structural.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,26 @@ import { arrayValidator } from '../../src/types/structural'
beforeAll(() => t.use(validatorSkeleton))

describe('array', () => {
beforeAll(() => t.use(arrayValidator))
beforeAll(() => t.use(ctx => {
ctx.use(arrayValidator)
ctx.use(stringValidator)
}))
test('base', () => {
const t0 = t(Array, String)

const output0 = t0.validate([''])
expect(output0).toEqual([''])
expectTypeOf(output0).toEqualTypeOf<string[]>()

const output1 = t0.validate(['', ''])
expect(output1).toEqual(['', ''])
expectTypeOf(output1).toEqualTypeOf<string[]>()

expect(() => {
// @ts-expect-error - TS2322: Type number is not assignable to type string
t0.validate([1])
}).toThrow('Data is unexpected')
})
})
describe('tuple', () => {
beforeAll(() => t.use(ctx => {
Expand Down

0 comments on commit bb5ad0a

Please sign in to comment.