UNPKG

just-submit

Version:

Submit simple form, with safe types, without management!

54 lines (51 loc) 2.37 kB
type FieldStrTypeMap = { string: string; number: number; date: Date; boolean: boolean; }; type FieldStrType = keyof FieldStrTypeMap; type Field = FieldStrTypeMap[FieldStrType]; type FormValues = Record<string, Field>; type FormValuesStrTypes = Record<string, FieldStrType>; type GetFormValuesFromStrTypes<TFormValuesStrTypes extends FormValuesStrTypes> = { [PField in keyof TFormValuesStrTypes]: FieldStrTypeMap[TFormValuesStrTypes[PField]]; }; type FormEvent = { preventDefault: () => void; currentTarget: unknown; }; type SubmitFn<TFormValues extends FormValues> = (data: TFormValues) => void | Promise<void>; /** * Creates a submission handler for a form with specified field types. * This function streamlines the process of handling form submissions by * automatically validating and parsing form data according to the provided * field type specifications. * * @param formValuesType - An object that maps each form field's name to its expected data type. * Supported data types are `string`, `number`, `date`, and `boolean`. * This mapping is used to parse the form data from string. * * @returns A function that can be used as an event handler for form submission. * This handler takes a callback function as an argument, which will be * called with the parsed form data if the validation is successful. * The form data is passed as an object with key-value pairs corresponding * to form field names and their parsed values. * * @example * const handleSubmit = createSubmit({ * fullName: 'string', * age: 'number', * birthday: 'date', * wantGift: 'boolean', * }); * const form = document.querySelector('form'); * form.addEventListener( * 'submit', * handleSubmit((data) => { * // ... * }), * ); */ declare const createSubmit: <TFormValuesStrTypes extends FormValuesStrTypes, TFormValues extends FormValues = GetFormValuesFromStrTypes<TFormValuesStrTypes>, TFormEvent extends FormEvent = FormEvent>(formValuesType: TFormValuesStrTypes) => (submitFn: SubmitFn<TFormValues>) => (formEvent: TFormEvent) => Promise<void>; export { type Field, type FieldStrType, type FieldStrTypeMap, type FormEvent, type FormValues, type FormValuesStrTypes, type GetFormValuesFromStrTypes, type SubmitFn, createSubmit };