Type a property in a store explicitly?

Viewed 327

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?
  }),
})
3 Answers

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,
  }),
})

My own answer would look something like this

import { defineStore } from 'pinia'

// define your store interface, you could use type instead
interface NotifyStoreState {
  message: string
  type: 'warning' | 'error' | 'success'
}

export const useNotifyStore = defineStore('NotifyStore', {
  // infer return type of state
  state: (): NotifyStoreState => ({
    message: '',
    type: ''
  }),
})
Related