Skip to content

Commit 76215de

Browse files
authored
Merge pull request #10 from Programmer-Network/improve-types
Improve validation result type
2 parents aa1b80d + 230a0d2 commit 76215de

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/index.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,15 @@ import { ajv as ajvInternal } from './utils/validation';
1010

1111
import { ErrorObject, JSONSchemaType, KeywordDefinition, SchemaObject } from 'ajv';
1212
import { useDebounce } from './Hooks/useDebounce';
13-
import { AJVMessageFunction, FormField, IState, UseFormReturn } from './utils/types';
13+
import {
14+
AJVMessageFunction,
15+
FormField,
16+
IState,
17+
UseFormReturn,
18+
ValidateResult,
19+
} from './utils/types';
1420
import Logger from './utils/Logger';
21+
1522
const useAJVForm = <T extends Record<string, any>>(
1623
initial: T,
1724
schema: JSONSchemaType<T> | SchemaObject,
@@ -114,7 +121,7 @@ const useAJVForm = <T extends Record<string, any>>(
114121
});
115122
};
116123

117-
const validateForm = () => {
124+
const validateForm = (): ValidateResult<T> => {
118125
const data = Object.keys(state).reduce((acc, inputName) => {
119126
acc[inputName as keyof T] = getValue(state[inputName].value) as T[keyof T];
120127
return acc;

src/utils/types.ts

+11-5
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,21 @@ export type InitialState<T> = {
4242
};
4343
};
4444

45-
export type ValidateResult<T> = {
46-
isValid: boolean;
47-
data: T | null;
48-
errors?: Partial<{ [K in keyof T]: T[K] }>;
49-
};
45+
export type ValidateResult<T> =
46+
| {
47+
isValid: true;
48+
data: T;
49+
}
50+
| {
51+
isValid: false;
52+
data: null;
53+
errors?: Partial<{ [K in keyof T]: T[K] }>;
54+
};
5055

5156
export type useFormErrors<T> = {
5257
[K in keyof T]?: string;
5358
};
59+
5460
export interface UseFormReturn<T> {
5561
data: T;
5662
state: IState<T>;

0 commit comments

Comments
 (0)