Member 'xyz' implicitly has an 'any' type. Error using react and typescript

Viewed 24

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.

enter image description here

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} />
  )
1 Answers

The problem is when you type ErrorMethods as an object with properties, you must also assign a type to each property within the object, so something like:

type TErrorMethods = { 
  setError: () => void, // whatever the type of setError should be
  clearError: () => void, // same as above
  errors: TError[] // same as above
};

// ...
validate:(values:string[], ErrorMethods: TErrorMethods) => void,
// ...
Related