Definitelytyped: [@types/react] input field should have ref property

Created on 28 Jun 2019  路  2Comments  路  Source: DefinitelyTyped/DefinitelyTyped

The following should work, but errors

function foo() { 
const inputRef = useRef();
return <input type="text" defaultValue="a default" ref={inputRef}/>
}
WARNING in [at-loader] ./src/App.tsx:25:65 
    TS2322: Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined'.
  Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLInputElement>'.
    Types of property 'current' are incompatible.
      Type 'undefined' is not assignable to type 'HTMLInputElement | null'.

Example: https://reactjs.org/docs/hooks-reference.html#useref

  • [X] I tried using the @types/xxxx package and had problems.
  • [X] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
  • [ ] I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).
  • [X] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see Definitions by: in index.d.ts) so they can respond.

    • Authors:

      @guilhermehubner

      @ferdaber

      @jrakotoharisoa

      @pascaloliv

      @Hotell

Most helpful comment

For anyone reading this, I should have used useRef<HTMLInputElement>(null), this fixes the problem

All 2 comments

For anyone reading this, I should have used useRef<HTMLInputElement>(null), this fixes the problem

Expected types:

  • string
  • ((instance: HTMLInputElement | null) => void)
  • RefObject<HTMLInputElement>
  • null
  • undefined

Passed in type

  • MutableRefObject<HTMLInputElement | null>

Still don't understand why these two can match?

Was this page helpful?
0 / 5 - 0 ratings