admin管理员组

文章数量:1295268

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: {},
})

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: {},
})
Share edited Feb 13 at 11:31 LazyOne 165k47 gold badges414 silver badges415 bronze badges asked Feb 12 at 6:35 泥瓦匠泥瓦匠 1388 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

本文标签: