ReactNative Animated.ScrollView ref TypeScript definition

Viewed 1796

In a React Native component, I have: <Animated.ScrollView ref={cardRef} ... />.

When I hover on top of ref I see (JSX attribute) React.ClassAttributes<Animated.ScrollView>.ref?: React.LegacyRef<Animated.ScrollView> | undefined, so I create the ref like so const cardRef = useRef<React.RefObject<Animated.ScrollView> | undefined>(undefined); but doing cardRef.current?.scrollTo({ x: newOffset }); gives me a warning for scrollTo: Property 'scrollTo' does not exist on type 'RefObject<ScrollView>'.

How can I know what the right TS definition of it should be? Is there a way or is it always a guessing game?

1 Answers

You are almost there. The generic type parameter on useRef is for the type that this is a ref to. In other words, the type of the .current property. You don't need to include RefObject in the generic because it already knows that it creates a RefObject. It just needs to know what type of RefObject it is creating.

Your current types are saying that it is creating a RefObject whose .current property is a RefObject and that ref's .current property is the ScrollView.

A little trick that you'll find from poking in the type declarations and examining error messages is that null is an acceptable value for any element ref. So you can use null as the initial value and you don't have to include | undefined in the type.

You should change:

const cardRef = useRef<React.RefObject<Animated.ScrollView> | undefined>(undefined);

to:

const cardRef = useRef<Animated.ScrollView>(null);
Related