Home > Blockchain >  key does not exsists in type 'StoreOptions<State>' Vuex 4 Vue 3 Typescript
key does not exsists in type 'StoreOptions<State>' Vuex 4 Vue 3 Typescript

Time:04-14

I want to set up a Vuex 4 Store with Typescript and Vue3. I have almost no experience with typescript.

I followed the Vuex Tutorial for the initial setup, almost copy paste. The only different element is that in my State interface I have a key of type Station.

I get this error

TS2345: Argument of type '{ station: {}; isOverlayActive: boolean; }' is not assignable to parameter of type 'StoreOptions<State>'.
  Object literal may only specify known properties, and 'station' does not exist in type 'StoreOptions<State>'.

This is my Station interface

export default interface Station {
  uuid: string;
  name: string;
  teaser: {
    src: string;
    title: string;
  };
  event: {
    uuid: string;
    name: string;
    logo: {
      src: string;
      title: string;
    };
  };
  logo: {
    src: string;
    title: string;
  };
  theme: {
    mainColor: string;
    textColor: string;
  };
}

and this is my index.ts where I'm defining the store, and where I get the error

import { InjectionKey } from "vue";
import { createStore, useStore as baseUseStore, Store } from "vuex";
import Station from "@/interfaces/station";

export interface State {
  station: Station;
  isOverlayActive: boolean;
}

export const key: InjectionKey<Store<State>> = Symbol();

export const store = createStore<State>({
  station: {}, // here the compiler shows the error
  isOverlayActive: false,
});

export function useStore(): Store<State> {
  return baseUseStore(key);
}

I think that the Station is not causing the problem, I tried also to set station: number in the Store interface and to set station: 0 in store but I get the same error.

What am I doing wrong? The goal is to have a typed store.

CodePudding user response:

In the createStore function you need to wrap it in the property state.

https://vuex.vuejs.org/guide/typescript-support.html#simplifying-usestore-usage

Instead of

export const store = createStore<State>({
  station: {}, // here the compiler shows the error
  isOverlayActive: false,
});

It's

export const store = createStore<State>({
  state: {
    station: {},
    isOverlayActive: false,
  }
});

It will still throw an error since uuid, name, etc. are not defined by {} but thats another error.

  • Related