使用打字稿设置Vuex商店状态

时间:2020-03-02 13:02:12

标签: typescript vue.js vuex

我是否可以用打字稿设置Vuex商店,但它是否为空?

我当前的代码是:

export default new Vuex.Store({
  strict: true,
  state: {
    username: string
  },
});

但是我目前得到:“'string'仅指类型,但在这里被用作值”。我知道我可以在用户名中放入一个字符串,但是我要求它为空。

1 个答案:

答案 0 :(得分:0)

export default new Vuex.Store({
    strict: true,
    state: {
      username: ""
    },
  });

这样,用户名被声明为字符串,并且开头仍然为空。

我个人还是会走以下路线:

/* location: '/src/models/state.ts': */
interface IState {
    username?: string;
}

/* location: '/src/store.ts': */
const state: IState = {username: undefined};

export default new Vuex.Store({strict: true, state});

这样,您可以更好地输入商店状态,并保留用户名undefined,如您的问题一样。您也不必记住检查未定义,因为IDE会提醒您,只要要将用户名用作字符串,都需要检查state.username !== undefined
因此,请考虑使用空字符串作为初始值,并通过删除界面中的undefined来禁止?