泥瓦匠
泥瓦匠

Reputation: 138

In WebStorm, when I click pinia state data, can not linked to use place

This a store named global and has state with three variables. I want to know where these variables are used. But I clicked these can't link to use place.

export const useGlobalStore = defineStore('global', {

state: () => {
    return {
        /**
         * 当前会话
         */
        currentChatRoom: {} as Room,
        /**
         * 点击选中的好友
         */
        currentSelectedFriend: {} as SelectedFriendItem,
        /**
         * 添加好友modal
         */
        addFriendModalInfo: {
            show: false,
            uid: null
        }
    }
},
actions: {},
})

Upvotes: 0

Views: 44

Answers (1)

tao
tao

Reputation: 90227

I'm not really sure why, but when using Typescript (which you seem to be using), code usages only work after you type the state, in a Pinia store. For example:

interface GlobalState {
  currentChatRoom: Room
  currentSelectedFriend: SelectedFriendItem
  addFriendModalInfo: {
    show: boolean
    uid: string | null
  }
}

export const useGlobalStore = defineStore("global", {
  state: (): GlobalState => ({
    currentChatRoom: {} as Room,
    currentSelectedFriend: {} as SelectedFriendItem,
    addFriendModalInfo: {
      show: false,
      uid: null
    }
  }),
  actions: {
    //...
  }
})

Now, when you Ctrl+Click on a state property, it takes you to the interface and when you Ctrl+Click on an interface property, it gives you the list of all usages.


As a side note, I strongly advise on replacing {} as Room with null and typing currentChatRoom as Room | null (undefined would work as well).
The casting pattern you're currently using allows for runtime errors which TypeScript cannot predict:

  • if/when Room has nested properties (e.g: currentChatRoom.owner.name)
  • when Room has callable methods which are not callable on an empty object (e.g: currentChatRoom.fetchCurrentUsers()).

TS's ability to inform you of potential runtime errors is, most likely, why you're using TS in the first place. Refrain from impairing its ability to help you.

Upvotes: 1

Related Questions