Skip to content

Commit

Permalink
fix: require validation functions with explicit type annotation for o…
Browse files Browse the repository at this point in the history
…ptional properties (#12)

## What?

When a property is optional, the property must have a corresponding
validation function.

## Why?

If there is no validation function, the value is actually `unknown`,
which contradics the type predicate.
  • Loading branch information
johannes-lindgren authored Apr 18, 2024
1 parent 97e2cd8 commit 0594fb6
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/pure-parse/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pure-parse",
"version": "0.0.0-beta.2",
"version": "0.0.0-beta.3",
"private": false,
"description": "Minimalistic validation library with 100% type inference",
"author": {
Expand Down
18 changes: 18 additions & 0 deletions packages/pure-parse/src/validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,24 @@ describe('validation', () => {
// string is more narrow than string | undefined, which means that if the validation passes for string, it satisfies User2
name: isString,
})
object<User2>({
id: isNumber,
// undefined is more narrow than string | undefined, which means that if the validation passes for undefined, it satisfies User2
name: isUndefined,
})
// @ts-expect-error
object<User2>({
id: isNumber,
// If we don't check the property, we have no type information on the field (it's unknown).
// Therefore, the fact that it's optional should not mean that we can skip validation
// name: isString,
})
object<User2>({
id: isNumber,
// Similarly to above; the property must have a corresponding validation function
// @ts-expect-error
name: undefined,
})
})
it('works with complex objects', () => {
type User1 = {
Expand Down
8 changes: 5 additions & 3 deletions packages/pure-parse/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,11 @@ export const tuple =
* @param schema maps keys to validation functions.
*/
export const object =
<T extends Record<string, unknown>>(schema: {
[K in keyof T]: Validator<T[K]>
}) =>
<T extends Record<string, unknown>>(
schema: Required<{
[K in keyof T]: Validator<T[K]>
}>,
) =>
(
data: unknown,
): data is {
Expand Down

0 comments on commit 0594fb6

Please sign in to comment.