TypeScript issues when creating ref for React Native TextInput
Asked Answered
C

1

22

I came across an issue when defining refs i.e.

inputRef = React.createRef(null)

//...

const someFunction () => {
 if (this.inputRef && this.inputRef.current) {
   this.inputRef.current.focus()
 }
}

//...

<TextInput ref={inputRef} />

When I access .focus() I get following error:

[ts] Property 'focus' does not exist on type 'never'. [2339]

Can I somehow tell createRef that this ref can be null or TextInput so it knows that .focus() may exist?

Caecilian answered 20/11, 2018 at 10:12 Comment(0)
E
37

You can try the following:

inputRef = React.createRef<TextInput>();
Eurythmics answered 20/11, 2018 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.