'React + Typescript - Refs typing errors

I have seen many other questions with the same problem as mine, and I have tried all solutions, but it is not working. I have a form with many inputs, which I have customized in FloatingLabelInputs. They have a public method called resetState, that I want to call. Here is what my component with the form looks like:

class EditModalPage extends React.Component<Props, State> {
  fieldsRefs: React.RefObject<FloatingLabelInput>[] = fields.map(() => React.createRef());

  render() {
    return fields.map((fieldData, index) => (
      <FloatingLabelInput
        name={fieldData.name}
        ref={this.fieldRefs[index]}
      />
    ));
  }
}

const fields = [
  { name: 'test' }
];

From what I've seen in other questions, this should work, as I have typed the fieldsRefs property using React.RefObject. However it doesn't, and the error TypeScript gives me is the following:

Type 'RefObject<FloatingLabelInput>' is not assignable to type 'string | (string & ((instance: HTMLInputElement | null) => void)) | (string & RefObject<HTMLInputElement>) | (RefObject<FloatingLabelInput> & string) | (RefObject<FloatingLabelInput> & ((instance: HTMLInputElement | null) => void)) | ... 5 more ... | undefined'.
  Type 'RefObject<FloatingLabelInput>' is not assignable to type '((instance: FloatingLabelInput | null) => void) & RefObject<HTMLInputElement>'.
    Type 'RefObject<FloatingLabelInput>' is not assignable to type '(instance: FloatingLabelInput | null) => void'.
      Type 'RefObject<FloatingLabelInput>' provides no match for the signature '(instance: FloatingLabelInput | null): void'.

If I try to console.log(this.fieldsRefs), everything is working, though. I just get the error and am forced to cast as any.



Solution 1:[1]

You should check the props interface for the <FloatingLabelInput /> component : it seems like it requires a ref of type RefObject<HtmlInputElement> and you are trying to give it a RefObject<FloatingLabelInput>.

You should try changing the type from React.RefObject<FloatingLabelInput> to React.RefObject<HtmlInputElement>

Solution 2:[2]

Try this type: React.MutableRefObject<HTMLInputElement | null>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 antoinechalifour
Solution 2 KFunk