Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2339: Property 'focus' does not exist on type '{}'. with React typescript

I have a typescript code for JSX class

export class SearchForm extends React.PureComponent<Props, State> {

  public inputRef: React.RefObject<{}>;

  constructor(props: any) {
    super(props)
    this.inputRef = React.createRef()
  }

  public componentDidMount(): void {
      this.inputRef.current.focus()
      this.inputRef.current.select()
  ...

Now when I try to compile this code, I have a bunch of errors:

ERROR in ...
TS2339: Property 'className' does not exist on type '{}'.

ERROR in ...
TS2339: Property 'focus' does not exist on type '{}'.

What is an issue?

like image 689
Roman Avatar asked Mar 25 '19 19:03

Roman


1 Answers

The error is in type definition of the inputRef: React.RefObject<{}>;, which is default suggestion for autofixing the type issue. Type RefObject<{}> is not assignable to type RefObject<HTMLInputElement>. Type {} is missing the following properties from type HTMLInputElement: accept, align, alt, autocomplete, and more.

The correct row for public inputRef: React.RefObject<{}>; should be:

  public inputRef: React.RefObject<HTMLInputElement>;

And the the piece of the code will look like:

export class SearchForm extends React.PureComponent<Props, State> {

  public inputRef: React.RefObject<HTMLInputElement>;

  constructor(props: any) {
    super(props)
    this.inputRef = React.createRef()
  }

  public componentDidMount(): void {
      this.inputRef.current.focus()
      this.inputRef.current.select()
  ...
like image 149
Roman Avatar answered Oct 14 '22 15:10

Roman