我想用Typescript和Vue3建立一個(gè)Vuex 4商店。我?guī)缀鯖]有打字的經(jīng)驗(yàn)。
我遵循Vuex教程進(jìn)行初始設(shè)置,幾乎是復(fù)制粘貼。唯一不同的元素是,在我的State
接口中,我有一個(gè)Station
類型的鍵。
我得到了這個(gè)錯(cuò)誤
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>'.
這是我的Station
接口
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;
};
}
這是我的index.ts
,在這里我定義了存儲(chǔ),在這里我得到了錯(cuò)誤
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);
}
我認(rèn)為Station
并沒有造成問題,我還試圖在Store
接口中設(shè)置station: number
,并在store
中設(shè)置station: 0
,但我得到了相同的錯(cuò)誤。
我做錯(cuò)了什么?目標(biāo)是建立一個(gè)類型化商店。
在
createStore
函數(shù)中,需要將其包裝在屬性state
中。https://vuex.vuejs.org/guide/typescript-support.html#simplifying-usestore-usage
Instead of
It's
它仍然會(huì)拋出一個(gè)錯(cuò)誤,因?yàn)?code>uuid、
name
等不是由{}
定義的,但這是另一個(gè)錯(cuò)誤。