简体   繁体   中英

Typescript Error and the spread operator arising from …props?

Hi I am running into issues when I am trying to use the spread operator with Typescript.

I have the function where the useFormikContext() and useField() functions are from Formik's library. When I add the //@ts-ignore everything works superbly as intended however, without that line I receive an error:

const DatePickerField = ({ ...props }) => {
  const { setFieldValue } = useFormikContext();
  //@ts-ignore
  const [field] = useField(props);
  return (
    <DatePicker
      {...field}
      {...props}
      selected={(field.value && new Date(field.value)) || null}
      onChange={(val) => {
        setFieldValue(field.name, val);
      }}
    />
  );
};
Argument of type '{ [x: string]: any; }' is not assignable to parameter of type 'string | (ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & FieldConfig<any>) | (ClassAttributes<...> & ... 1 more ... & FieldConfig<...>) | (ClassAttributes<...> & ... 1 more ... & FieldConfig<...>)'.
  Type '{ [x: string]: any; }' is not assignable to type 'ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & FieldConfig<any>'.
    Property 'name' is missing in type '{ [x: string]: any; }' but required in type 'FieldConfig<any>'.  TS2345

From what I understand this function accepts a spread operator, so that is meant to say it accepts an object / array with 0 or more properties. it automatically got assigned the type { [x: string]: any; } { [x: string]: any; } which is meant to say that there is a key (x) with a value type of any. However, I don't know how to fix this error given by typescript.

Okay after some researching here is what I found to fix the errors.

The syntax '{ [x: string]: any; }' is letting me know that this object has a key of x which is a string with a value of any. I didn't know this at the time of the question I was confused a little bit. https://www.typescriptlang.org/docs/handbook/advanced-types.html <-- index types and index signatures

Typescript was also letting me know that the useField() function required the property name of value string. so I typed it using this newfound knowledge and got rid of an unused function selected and the new code now looks like this:

const DatePickerField = ({ ...props }: { [x: string]: any; name: string }) => {
  const { setFieldValue } = useFormikContext();

  const [field] = useField(props);
  return (
    <DatePicker
      {...field}
      {...props}
      // selected={(field.value && new Date(field.value)) || null}
      onChange={(val) => {
        setFieldValue(field.name, val);
      }}
    />
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM