Why typescript occurs compile error with using the surrounded constant condition?

Viewed 27

I'm always curious about when the union-type condition handling in Typescript with React-native is used, If I used const with surrounding conditions, Typescript does not detect the inner condition of const. It must exist within the same scope for it to work.

Why it occurs compile error?

example

  import {isNull} from 'lodash';

  ...,

  const scrollViewRef = useRef<ScrollView | null>(null)

  const onPressFooter = useCallback(() => {
    if (isNull(scrollViewRef)) return; --> b line show compile error
    if (scrollViewRef === null) return; --> b line not occurs error 

    scrollViewRef.current.scrollTo({y :0, animated : true}) // -> b
  }, [])

1 Answers

useRef is object type value, which have properties by default. So your generic types <ScrollView | null> is used to type scrollViewRef.current property.Can you try to change your null check condition to this?

if (isNull(scrollViewRef.current)) return;
Related