Jump to content
Search Community

gabriel.ortiz

Members
  • Posts

    23
  • Joined

  • Last visited

Community Answers

  1. gabriel.ortiz's post in Declare method types (with typescript) on GSAP context object was marked as the answer   
    Thanks so much @GreenSock! I appreciate your response!
     
    So I got something working for me in case others might encounter the same situation with context. I ended up modifying the react Gsap context hook to cast the return context types with an optional object that you can pass in through a generic
     
    /** * Wrapper hook initializes GSAP context object * * @param {RefObject} * @param {gsap.ContextFunc} * @returns {gsap.Context} */ export function useGsapContext< T extends HTMLElement = HTMLDivElement, R extends Record<string, unknown> = Record<string, unknown>, // It's ok to allow an empty function since gsap.context() needs a function argument to initialize // eslint-disable-next-line @typescript-eslint/no-empty-function >(scope?: RefObject<T>, context: gsap.ContextFunc = () => {}) { return useMemo( () => gsap.context(context, scope), // It's not necessary to list `context` as a dependency // eslint-disable-next-line react-hooks/exhaustive-deps [scope], /** * Normally its hacky to type assert - but since this context logic is * isolated in this hook there is little risk for these types causing issues * with other implementations of GSAP context */ ) as Partial<R> & gsap.Context; } /** * These types will be added to the return of the gsap context so typescript * will know to expect these properties if referenced later */ type ContextMembers = { newTab: (newTabKey: string, oldTabKey: string | null) => void; }; const wrapperRef = useRef<HTMLDivElement>(null); const ctx = useGsapContext<HTMLDivElement, ContextMembers>(wrapperRef); useEffect(()=>{ ctx.add("newTab", (newTabKey: string, oldTabKey: string | null) => {....}) }, []); useEffect(()=>{ ctx.newTab("foo", "bar"); },[tabState]);  
     
    Additionally, I noticed gsap.context() will return undefined if no function argument is passed in. Is this expected? The Context types have the callback function as optional argument, and but it appears to be required type argument or else nothing is initialized.
    // gsap-core.d.ts function context(func?: ContextFunc, scope?: Element | string | object): Context; Correct me if i'm wrong - but it could possibly be defined like this:
    function context(func: ContextFunc, scope?: Element | string | object): Context;  
×
×
  • Create New...