首页 > 解决方案 > Vuex - 存储状态对象的类型未知

问题描述

/src/middlewares/auth.ts 文件:

import store from '@/store'

export default {
  guest(): void {
    if (store.state.auth.authenticated === false) {
      // do some action
    }
  }
}

/src/store.ts 文件:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    auth
  }
})

/src/store/auth.ts:

import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'

@Module
export default class Auth extends VuexModule {
  public authenticated: boolean = false
}

但是我收到 TS 错误:Object is of type 'unknown'

然后我的npm run build失败。我怎样才能打字store,这样这个错误就会消失?

更新 1

问题是:if (store.state.auth.authenticated === false)

在此处输入图像描述

更新 2

我对这 3 个文件的目录结构:

更新 3

如果我store.state.auth.authenticated改为store.state然后编译器停止抱怨,我认为它与我的商店 auth.ts 文件有关,我需要以某种方式输入定义。

标签: javascripttypescriptvue.jsvuex

解决方案


看一看:logrocket

export default function auth ({ next, store }){
 if(!store.getters.auth.loggedIn){
     return next({
        name: 'login'
     })
 }

 return next()
}

您的第一个参数应该是定义 { store } 的对象

export default guest ({ store }, to: any ...){

推荐阅读