Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add getFieldPath a function that helps with path name typings #511

Merged
merged 1 commit into from
Jul 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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('.');
}
Loading