vue-i18n icon indicating copy to clipboard operation
vue-i18n copied to clipboard

Make fallback locale iterable

Open jtuchel opened this issue 2 years ago • 0 comments
trafficstars

Clear and concise description of the problem

Given a sample configuration

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

and sample code

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];
    }

    /*
    if (fallbackLocale.value in myRecord) {
      return myRecord[fallbackLocale.value];
    }
    */

    throw new Error('missing translation...');
}

I want to read the correct message from myRecord ( this record comes from an external API ) but this is not possible because fallbackLocale.value does not return a string ( because there might be multiple fallback locales ) so the second if-statement is invalid TS code.

Currently it is not possible to retrieve a message via fallback locale.

Suggested solution

If fallbackLocale was iterable this might work

    for (const currentFallbackLocale in fallbackLocale.value) {
      if (currentFallbackLocale in myRecord) {
        return myRecord[currentFallbackLocale];
      }
    }

Alternative

Since I know that the fallbackLocale is not an array I can cast it to a string

fallbackLocale.value as string

This is a temporary fix for this case but I don't like it...

Additional context

No response

Validations

jtuchel avatar Dec 23 '22 09:12 jtuchel