2

I'm using vue-i18n for my Vue 3 app. The app is configured like so

const i18n = createI18n({
  legacy: false,
  locale: "en",
  fallbackLocale: "en",
});

Inside my component I'm using

import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();

where locale.value returns a string, but fallbackLocale.value returns a custom type. https://vue-i18n.intlify.dev/guide/essentials/fallback.html#fallbacking shows that there might be multiple locales.

Since I could check against each fallback locale I need to find a way to iterate fallbackLocale. Currently I wasn't able to figure out how, a for...in loop didn't work for me, it says

TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'FallbackLocales '.


My usecase:

An external API returns a Record of locales and their messages. Based on my settings I want to read the translated message from it:

import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();

const myRecord: Record<string /* locale */, string /* text */> = { "en": "title", "de": "titel" };

function getContent(): string {
    if (locale.value in myRecord) {
      return myRecord[locale.value];
    }

    // try the fallback locales before throwing an error...

    throw new Error('missing translation...');
}
baitendbidz
  • 187
  • 3
  • 19
  • You should not care about the fallback locale, i18n will handle it, simply ask the translation you need and it will give you the translation, from the locale or from the fallback if it does not exist – Lk77 Dec 23 '22 at 10:16
  • @Lk77 yes, you are right. But in this case, I get a record of messages from an external API and want to read the translated content from it ( I updated my question ) – baitendbidz Dec 23 '22 at 10:37

0 Answers0