Search code examples
typescriptnuxt.jsvue-i18nnuxt-i18n

nuxt-i18n: Lang Switcher Error "Object is possibly 'undefined'


I want to build a language switcher on my nuxt app with nuxt-i18n plugin. Important note is, that I am using TypeScript instead of JavaScript.

As in the documentation (https://i18n.nuxtjs.org/lang-switcher) I implemented the following code into my Navbar component:

TheNavbar.vue

<template>
  <nav class="navbar">
    <div class="container">
      <div>
        <NuxtLink
          v-for="locale in availableLocales"
          :key="locale.code"
          :to="switchLocalePath(locale.code)">{{ locale.name }}
        </NuxtLink>
      </div>
    </div>
  </nav>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  name: "TheNavbar",
  computed: {
    availableLocales() {
      return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale);
    }
  }
})

In my app this solution works. But the console prints out the two following errors:

 ERROR  ERROR in src/components/shared/TheNavbar.vue:25:14                                                                                                                                                       18:49:05
TS2532: Object is possibly 'undefined'.
    23 |   computed: {
    24 |     async availableLocales() {
  > 25 |       return this.$i18n.locales.filter(i => i?.code !== this.$i18n.locale);
       |              ^^^^^^^^^^^^^^^^^^
    26 |     }
    27 |   }
    28 | })


ERROR in src/components/shared/TheNavbar.vue:25:48
TS2339: Property 'code' does not exist on type 'string | LocaleObject'.
  Property 'code' does not exist on type 'string'.
    23 |   computed: {
    24 |     async availableLocales() {
  > 25 |       return this.$i18n.locales.filter(i => i?.code !== this.$i18n.locale);
       |                                                ^^^^
    26 |     }
    27 |   }
    28 | })

My i18n configuration in nuxt.config.js:

  i18n: {
    locales: [
      {
        code: 'de',
        name: 'Deutsch',
      },
      {
        code: 'en',
        name: 'English'
      }
    ],
    defaultLocale: 'de',
    vueI18n: {
      fallbackLocale: 'de',
      messages: {
        de: {
          welcome: 'Willkommen'
        },
        en: {
          welcome: 'Welcome'
        }
      }
    }
  },

Solution

  • Try this:

    <NuxtLink
       v-if="availableLocales"
       v-for="locale in availableLocales"
       :key="locale.code"
       :to="switchLocalePath(locale.code)">{{ locale.name }}
    </NuxtLink>