Pinia / TypeScript Access getters from action — Property does not exist on type
Asked Answered
C

2

5

I have a store.

export const useGameStore = defineStore("game", {
  state: () => gameBaseState,
  getters: {
    foundMarkers(state): Marker[] {
      return state.markers.filter((m) => m.found);
    },
    ...
  },
  actions: {
    closeAll() {...},

    nextMissed() {...},

    previousMissed() {...},

    removeFlashId(id: string) {...},

    guess(pos: Coord) {
      ...

      if (this.foundMarkers.length >= this.toFind) {
        this.setScore();
        this.status = GameStatus.Passed;
      }
    },
  },
});

In the guess() action and all over the other actions the getter values aren't found. I get...

Property 'foundMarkers' does not exist on type '{ closeAll(): void; nextMissed(): 
void; previousMissed(): void; removeFlashId(id: string): void; flash(text: string, 
type?: string, t?: number): void; loadLevel(levelIndex: any): void; ... 10 more ...; 
guess(pos: Coord): void; } & { ...; } & _StoreWithState<...> & _StoreWithGetters<...> 
& PiniaCustomProperties<...>'.

Which is basically all the actions. It seems like it can't infer the type of the getters (all the code runs fine, and all the getters can be accessed fine).

Have I missed something?

So far I have made sure that the foundMarkers getter is typed

foundMarkers(state): Marker[] {
                     ^^^^^^^^

As recommended in other forums, but beyond this I'm a bit lost in how to correctly format this.

I have also checked that the actions themselves are formatted correctly (and I think they are).

Chadbourne answered 16/3, 2023 at 11:47 Comment(0)
C
12

Answer: Make sure every single getter has a return type, otherwise the parser won't be able to find any of them.

While it was obvious from answers like this:

https://github.com/vuejs/pinia/discussions/1299

You need to type the return:

totalDiscount(): number | undefined {
  return this.subTotal;
},

The solution was to add the return type to the getter, it wasn't obvious I needed to type the return of EVERY getter. It must have been that the first one without a type caused all subsequent getters to fail.

I blame my lack of understanding / newness to typescript.

Chadbourne answered 16/3, 2023 at 11:58 Comment(0)
H
0

You can always stop the check if it bothers you by adding

// @ts-nocheck

at the beginning of the file.

Hardener answered 29/5 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.