简体   繁体   中英

Typescript Object is possibly 'null' focusing using ref in react

typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

myRef && myRef.current && myRef.current.focus();

if I use

myRef?.current?.focus();

I got

Property 'focus' does not exist on type 'never'.ts(2339)

When you define your reference, you should specify what type it will be:

const myRef = useRef<HTMLElement>(null);

(Note that the above assumes you're using it like <div ref={myRef}> - if you're setting myRef.current manually, you need to specify the type as <HTMLElement|null> .

Once you have done this, you should be able to use the following:

myRef.current?.focus()

Note that you do not need to use the existential check on myRef - that will always be an object with a current property - that's how react's API works.

To make typescript silent and tell typescript you know what you are doing. you can use exclamation mark(!) before the variable you know that it can be null . Like in existing scenario if "current" can be null in some scenarios and you want that typescript do not show error on it.

myRef.!current.focus()

Optional chaining is a better way to deal with such statements. This should not give you any error:-

myRef?.current?.focus()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM