TL;DR Has anyone have any examples what the correct generic is for useAnimatedGestureHandler?
Problem:
I am following this tutorial on Reanimated 2 gestures animation. There's this example:
//...
const onGestureEvent =
useAnimatedGestureHandler({
onStart: (_, ctx) => {
ctx.offsetX = translateX.value
},
//...
})
//...
i use typescript, when i copy the example in typescript i get ctx
argument (context) type error:
Property 'offset' does not exist on type '{}'.
After some snooping around in onStart declaration i found that full type for GestureHandlers require a generic <T, TContext extends Context>
:
//...
export interface GestureHandlers<T, TContext extends Context> {
onStart?: Handler<T, TContext>;
//...
}
Workaround:
i was able to work around this problem by simply passing a utility type Record (which is almost the same as saying 'any') , i don't like this.
const onGestureEvent = useAnimatedGestureHandler<
GestureEvent<PanGestureHandlerEventPayload>,
Record<string, unknown>
>({
onStart: (_, ctx) => {
ctx.offsetX = translateX.value;
},
// onActive: () => {},
// onEnd: () => {},
});
Question:
Has anyone have any examples what the correct generic is for useAnimatedGestureHandler?
According to the documentation, context
is "a plain JS object that can be used to store some state" that "you can read and write any data to". You are simply expected to define the interface of your state yourself.
The source repository has an Example project that demonstrates this. For instance, here and here are two examples where they define an AnimatedGHContext
type that they pass as the generic.
So in your case, you would define and pass a type such as the following:
type AnimatedGHContext = {
offsetX: number;
};