In a Pinia store, how can one explicitly type a property?
import { defineStore } from 'pinia'
export const useNotifyStore = defineStore('NotifyStore', {
state: () => ({
message: '',
type: '', // only 'warning', 'error', 'success' shall be allowed values -> how can I specify that?
}),
})
CodePudding user response:
export type RootState = {
message: string;
type: string;
};
export const useMainStore = defineStore({
id: "mainStore",
state: () =>
({
message: '',
type: '',
} as RootState),
// rest of your logic
From this tutorial: https://dev.to/carlomigueldy/getting-started-with-vue-3-pinia-store-typescript-by-building-a-grocery-list-app-19km
CodePudding user response:
You can declare a type with a typescript cast as type
.
import { defineStore } from 'pinia'
type messageType = '' | 'warning' | 'error' | 'success';
export const useNotifyStore = defineStore('NotifyStore', {
state: () => ({
message: '' as string,
type: '' as messageType,
}),
})