E
E
Evgeny Zhurov2021-06-09 02:34:39
typescript
Evgeny Zhurov, 2021-06-09 02:34:39

How to fix "No index signature..." error when accessing object properties?

Type declarations:

type AuthMessagesKeys = 'login' | 'logout' | 'session'

type AuthMessagesValues = 'text' | 'type'

type AuthMessagesParams = {
  [P in AuthMessagesValues]: string
}

type AuthMessages = {
  [P in AuthMessagesKeys] : AuthMessagesParams
}

export { AuthMessages }


Usage in Nuxt component:

import Vue, { PropOptions } from 'vue'
import { AuthMessages } from '@/types/Auth'

export default Vue.extend({
  mounted() {
      const queryObject = this.$route.query
      const queryKey: string = queryObject.message

      if (message) {
          const messageType = this.messages[queryKey].type // здесь
          const messageText = this.messages[queryKey].text // и здесь - ошибка (см. ниже) 
          ...
      }
    },

    data() {
      return {
        messages: {
          login: {
            text: 'You have to be logged in',
            type: 'warning'
          },

          logout: {
            text: 'You have successfully logged out',
            type: 'success'
          },

          session: {
            text: 'Your session has been expired',
            type: 'error'
          }
        } as PropOptions<AuthMessages>
      }
    }
})


this.messages[queryKey]An error occurs in expressions :

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PropOptions'.
No index signature with a parameter of type 'string' was found on type 'PropOptions'


In principle, it is clear what is meant, but it is not clear how to change the code to remove the error.
I found several articles and videos on the topic of indexed types, but I still can’t figure out what to do in this particular case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-06-09
@Aetae

const queryKey: AuthMessagesKeys = queryObject.message

This will work, but it's not reliable - because it can crash at runtime if something left arrives in message.
It's better to write a typeguard like
function isAuthMessagesKey(str: string): str is AuthMessagesKeys {
  return ['login', 'logout', 'session'].includes(str); 
}

and check before use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question