在商店中明确输入 属性?

Type a property in a store explicitly?

在 Pinia 商店中,如何显式键入 属性?

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?
  }),
})
export type RootState = {
  message: string;
  type: string;
};

export const useMainStore = defineStore({
  id: "mainStore",
  state: () =>
    ({
      message: '',
      type: '',
    } as RootState),
// rest of your logic

来自本教程:https://dev.to/carlomigueldy/getting-started-with-vue-3-pinia-store-typescript-by-building-a-grocery-list-app-19km

您可以使用打字稿强制转换声明类型 as type

import { defineStore } from 'pinia'

type messageType = '' | 'warning' | 'error' | 'success';

export const useNotifyStore = defineStore('NotifyStore', {
  state: () => ({
    message: '' as string,
    type: '' as messageType,
  }),
})