将 Vue 3 与 Vuex 4 一起使用时的打字稿问题

Typescript issue when using Vue3 with Vuex4

TS2345:'StoreOptions' 类型的参数不可分配给 'Plugin_2' 类型的参数。 属性 'install' 在类型 'StoreOptions' 中缺失,但在类型 '{ install: PluginInstallFunction; 中是必需的}'.

const app = createApp(App)
app.use(store, key)
app.use(router)
app.use(...)
app.mount("#app")

商店:

export interface RootState {}
const state: RootState = {}

export interface TypeState extends RootState {
  markdown: MarkdownState
  user: UserState
  fileTree: FileTreeState
  editor: EditorState
}

export const key: InjectionKey<Store<TypeState>> = Symbol("storeKey")
export const store: StoreOptions<RootState> = createStore({
  state,
  modules: {
    markdown,
    user,
    fileTree,
    editor,
  },
  plugins: [
    createPersistedState({
      paths: ["user", "fileTree", "markdown"],
    }),
  ],
})

export function useStore() {
  return baseUseStore(key)
}

尝试这样定义您的商店:

export const store = createStore<RootState>({
  // ...
});

app.use 方法需要一个 Vue 插件作为它的第一个参数。 Vue 插件是一个带有 install 方法的对象。在这种情况下,Vuex 中的 Store class 的一个实例。

here 所示,createStore 方法的 return 类型是 Store。这就是你想要的。因此无需为 store 变量指定类型。您唯一需要做的就是将您的状态类型提供给上述 createStore 方法。