Skip to content

Commit

Permalink
Make nonEmpty easier to use
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexGalays committed Apr 21, 2021
1 parent 02edd47 commit 2927838
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "idonttrustlikethat",
"version": "2.0.1",
"version": "2.0.2",
"sideEffects": false,
"description": "Validation for TypeScript",
"license": "MIT",
Expand Down
9 changes: 7 additions & 2 deletions src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,9 @@ type HasSize =
| Map<unknown, unknown>
| Set<unknown>

export function minSize<T extends HasSize>(minSize: number) {
export function minSize<T extends HasSize>(
minSize: number
): (value: T) => Result<string, T> {
return (value: T) => {
const size =
typeof value === 'string'
Expand All @@ -667,4 +669,7 @@ export function minSize<T extends HasSize>(minSize: number) {
}
}

export const nonEmpty = <T extends HasSize>() => minSize<T>(1)
// Note: this a fully fledged function so that inference on T will work.
export function nonEmpty<T extends HasSize>(value: T): Result<string, T> {
return minSize<T>(1)(value)
}
16 changes: 9 additions & 7 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -840,24 +840,26 @@ describe('validation core', () => {
printErrorMessage(notOkValidation3)
})

it('returns the correct type for nonEmpty', () => {
it('can validate that a container is not empty', () => {
const array = [1, 2, 3]
type ArrayType = typeof array
const okValidation = v.array(v.number).and(nonEmpty()).validate(array)
const okValidation = v.array(v.number).and(nonEmpty).validate(array)

const obj = { a: 'a' }
type ObjType = typeof obj
const okValidation2 = v
.object({ a: v.string })
.and(nonEmpty())
.validate(obj)
const okValidation2 = v.object({ a: v.string }).and(nonEmpty).validate(obj)

const notOkValidation = v.object({ a: v.string }).and(nonEmpty).validate({})

if (okValidation.ok && okValidation2.ok) {
// Check assignation/type
// Type assertion.
const _arrayType: ArrayType = okValidation.value
const _objType: ObjType = okValidation2.value
} else {
throw new Error()
}

expect(notOkValidation.ok).toBe(false)
})
})

Expand Down

0 comments on commit 2927838

Please sign in to comment.