ReactJS and Typescript : refers to a value, but is being used as a type here (TS2749)

Answerrer picture Answerrer · May 28, 2020 · Viewed 15.9k times · Source

I'm coding a ReactJS class with Typescript and Material-ui, in a .tsx file. In one of my custom components, I want to create a reference to one of the components that I use in my custom component.

export class MyTextField extends React.Component<MyProps, MyState> {
  private refTextField: React.RefObject<TextField>;
  constructor(props: MyProps) {
    super(props);
    this.refTextField = React.createRef();
  }

  render(): JSX.Element {
    const { id, label, value: defaultValue } = this.props;
    const { value } = this.state;
    const element = (
      <TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} />
    );

    return element;
  }
}

During compilation, I get an error on the declaration of my reference:

'TextField' refers to a value, but is being used as a type here. TS2749

I tried to put "typeof TextField" in my declaration, but I have another message, when valuing the ref property in my render :

Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type '((instance: HTMLDivElement | null) => void) | RefObject | null | undefined'. Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type 'RefObject'. Type '(props: TextFieldProps) => Element' is missing the following properties from type 'HTMLDivElement': align, addEventListener, removeEventListener, accessKey, and 238 more. TS2322

Any ideas ? thank you so much

Answer

jonyB picture jonyB · Oct 11, 2020

Make sure you're on a .tsx file and not a .ts file