I am using React useForm hook and typescript. For validation I am using setError, clearError and created types for it. But I am getting error "Member 'xyz' implicitly has an 'any' type.".
I can resolve this error by make "noImplicitAny" false in tsconfig.json But I dont want to do this.
Form.tsx
export type ErrorMethods={
setError:any, clearErrors:any, errors:any
}
export type FormInputs = {
firstName: string
lastName: string
email: string
};
interface FieldsProps {
fields: Fields[],
onSubmit:(values:any)=>void,
validate:(values:string[], ErrorMethods:{setError, clearErrors, errors})=>void,
watchFields: string[]
}
const Form = ({fields, onSubmit, watchFields, validate }: FieldsProps) => {
const {register, handleSubmit, watch, setError, clearErrors, formState: {errors}} = useForm();
const watchValues = watch(watchFields)
validate(watchValues, {setError, clearErrors, errors})
// console.log(watchValues);
const renderFields =(fields:Fields[])=>{
return fields?.map((field)=>{
let { type, name, validationProps } = field;
switch (type) {
case 'text':
return (
<div key={name}>
<TextfieldWrapper type='text' {...register(`${name}`, validationProps)} name={name} id={name} {...field}/>
<> { console.log('last N', errors[`${name}`]?.message)}</>
<>{errors[`${name}`]?.message && <span className='error'>{" " + errors[`${name}`]?.message + " "}</span>} </> {/* Error in this line */}
</div>
)
JobForm.tsx
//Watch Values
const validate=(watchValues: string[], errorMethods:ErrorMethods)=>{
const {errors, setError, clearErrors} = errorMethods;
//First Name Validation
if(watchValues['firstName' as unknown as number] === 'Admin'){
if(!errors['firstName']){
setError('firstName', {
type: 'manual',
message: 'You cant use this First Name'
})
}
}
console.log(watchValues);
}
return (
<Form fields={fields} watchFields={['firstName']} validate={validate} onSubmit={onSubmit} />
)
