Search code examples
typescriptpinia

Type a property in a store explicitly?


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

Solution

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