vue-i18n
vue-i18n copied to clipboard
Make fallback locale iterable
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
- [X] Read the Contributing Guidelines
- [X] Read the Documentation
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.