Skip to content

Commit

Permalink
feat: add getFieldPath a function that helps with path name typings (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
yoannfleurydev authored Jul 25, 2024
1 parent e333149 commit 50a42bf
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/lib/form/getFieldPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { FieldPath, FieldValues } from 'react-hook-form';

/**
* Use this function to build a path for a form. This function will type check
* the name to make sure you don't have typo or inexistant field path.
*
* Example:
* ```
* const zPasswordForm = () => z.object({ currentPassword: z.string(), newPassword: z.string() });
* type PasswordForm = z.infer<ReturnType<typeof zPasswordForm>>;
*
* zPasswordForm()
* .superRefine((obj, ctx) => {
* if (obj.currentPassword === obj.newPassword) {
* ctx.addIssue({
* code: z.ZodIssueCode.custom,
* path: getFieldPath<PasswordForm>('currentPassword'), // typed checked
* message: 'The password should not be the same',
* });
* }
* })
*
* ```
* @param name The name that will be type checked and split.
* @returns The array made from the name (splitted on '.')
*/
export function getFieldPath<TFieldValues extends FieldValues>(
name: FieldPath<TFieldValues>
) {
return name.split('.');
}

0 comments on commit 50a42bf

Please sign in to comment.