Search code examples
typescriptvue.jsvuejs3piniavueuse

Typescript annotation of Pinia state persisted with useLocalStorage()


In my pinia based store I have state with following properties:

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLoginStore = defineStore('login', () => {
  // State
  const isAuthenticated = useLocalStorage('isAuthenticated',false)
  const user = ref<{ name: string; email: string } | null>(null)
  const accessToken = ref<string | null>(null);

  // Actions
  const login = (userData: { name: string; email: string }, token: string) => {
    user.value = userData
    isAuthenticated.value = true
    accessToken.value = token
  }

  const logout = () => {
    user.value = null
    isAuthenticated.value = false
    accessToken.value = null;
  }

  return {
    isAuthenticated,
    user,
    accessToken,
    login,
    logout,
  }
})

Based on the VueUse docs I modified the first value as follows, since it infers simple types, but can't figure out how to explicitly pass more complex type annotations:

...
// State
const isAuthenticated = useLocalStorage('isAuthenticated', false)
const user = ???
const accessToken = ???
...

EDIT: added whole Pinia store for clarity


Solution

  • So the answer was rather obvious, but I am fairly beginner when it comes to TypeScript type annotation syntax. Hopefully this will save someone some time:

      const isAuthenticated = useLocalStorage('isAuthenticated', false)
      const user = useLocalStorage<{ name: string; email: string } | null>('user', null)
      const accessToken = useLocalStorage<string | null>('accessToken',null)