Jump to content
Search Community

Problem typing contextSafe (Typescript)

TimTh test
Moderator Tag

Go to solution Solved by GreenSock,

Recommended Posts

I am stumped trying to correctly type my animation functions when wrapped in contextSafe. You can see an example of my problem here on StackBlitz. In it I’m trying to reproduce a simple version of Animating on interactions with callbacks as shown in the first method of using contextSafe in the Animating on interaction section of the Using GSAP with React page in the docs. I’ve got two simple rotation animations, a square and a circle. The circle is wrapped in contextSafe and the square is not. Both animations work correctly, but the circle throws the TS error “Type 'Function' is not assignable to type 'MouseEventHandler<HTMLDivElement>'.” on the onClick of the circle div. I’ve tried a bunch of different ways of typing the contextSafe function but none seem to work.

 

Does anyone have any insights into what I’m missing, or any examples of TypeScript implementations of contextSafe and useGSAP?

 

Thanks for any help!

See the Pen ZEKJPLa by GreenSock (@GreenSock) on CodePen

Link to comment
Share on other sites

  • Solution

That looks like just a TypeScript thing. You've gotta cast your function to be what React expects:

const onEnterSafe = contextSafe(() => {
  ...
}) as React.MouseEventHandler; // <-- this is the key

https://stackblitz.com/edit/gsap-interaction-ibz4fr?file=app%2Fpage.tsx,node_modules%2F%40types%2Freact%2Fts5.0%2Findex.d.ts

 

Better? 

Link to comment
Share on other sites

Thanks Jack, that was super helpful. I had tried typing it as a MouseEventHandler in a different way and it didn't work, but the syntax you provided did. Really appreciate it!

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...