#TS (7022) Getting reference error when trying to use instance variable in callback

10 messages · Page 1 of 1 (latest)

coral marlin
#

I'm trying to integrate this library (react-query-kit) in a codebase. It's is a library built around @tanstack/react-query. The issue now is that whenever I try to use the variable of the router to invalidate a query, I get TS (7022) reference error from Typescript even though everything seems to be working.

Here's a sample code demonstrating the issue.

https://codesandbox.io/p/sandbox/react-query-kit-invalidate-ref-error-yr4cqq?file=%2Fsrc%2Froutes.ts%3A14%2C14-14%2C19

Any Idea how to fix the error? Only approach that seem to work is defining the property as any which isn't ideal.

split crane
#

@coral marlin in this case just remove the return keyword from onSuccess or else give onSuccess an explict return type

#

basically what is happening here is in order for typescript to infer the type of posts it needs to evaluate the return type of all of those methods you have defined

#

however, in onSuccess you probably unnecessarily are returning a value that uses posts

#

which means that the evaluation of the type of post depends upon the type of post

#
    onSuccess() {
      queryClient.invalidateQueries({
        queryKey: posts.getPosts.getKey(),
      });
    },
#

or

    onSuccess(): Promise<void> {
      return queryClient.invalidateQueries({
        // reference error caused by this line
        queryKey: posts.getPosts.getKey(),
      });
    },
#

either will work

#

looks like invalidateQueries returns Promise<void>, so may as well do the latter

coral marlin
#

Thanks alot for taking your time to explain, this make total sense. I understand what's going on alot better now.