Infer type in rules for custom react hook form component using useController

22 views Asked by At

I've devised a custom component that accepts UseControllerProps as its props, structured as follows:

type CustomComponentProps<T extends FieldValues> = UseControllerProps<T>;

This component can be utilized as follows:

function CustomComponent<T extends FieldValues>({
  control,
  name,
  rules,
  ...props
}: CustomComponentProps<T>) {
  // implementation of the component
}

Within the component, I use useController in the following manner:

const { field } = useController<T>({
  control,
  name,
  rules,
});

For my form, I've created the subsequent values:

type FormValue = {
  input1: string;
  input2: number:
  input3: boolean;
};

When using the CustomComponent, I can do so as follows:

const { control } = useForm<FormValue>();

<CustomComponent
  control={control}
  name="input2"
/>

This works just fine. However, when I attempt to define validation rules, the arguments received in the validation are of type string | number | boolean.

<CustomComponent
  control={control}
  name="input2"
  rules={{
    validate: {
      // value is of type 'string' | 'number' | 'boolean'
      someValidation: (value) => value || 'error',
    },
  }}
/>

Given that I've specified the name as input2, we are already aware that the type should be a number. How can I instruct CustomComponent to use the property name to infer the type of value?

0

There are 0 answers