Typescript Error and the spread operator arising from …props?

这一生的挚爱 提交于 2020-04-30 06:40:07

问题


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; } 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.


回答1:


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);
      }}
    />
  );


来源:https://stackoverflow.com/questions/61312273/typescript-error-and-the-spread-operator-arising-from-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!