1

在 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?
  }),
})
4

2 回答 2

1
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

于 2022-02-19T21:14:12.837 回答
1

您可以使用 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,
  }),
})
于 2022-02-19T21:17:11.587 回答