Welcome to my first question!
I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhere to a specific type or interface.
Initially, I attempted the following:
interface Text {
[key: string | number]: ComponentText | Language;
}
interface Language {
[key: string]: string;
}
text: Text = {
title: {
en: "English text",
sv: "Swedish text",
fr: "French Text",
es: "Spanish Text",
}
paragraph: {
subText: {
en: "English text",
sv: "Swedish text",
fr: "French Text",
es: "Spanish Text",
}
}
}
// getCurrLang(s: any) handles getting the correct language string or throws an error when "s" isn't "Language".
However, I encountered errors when trying to retrieve
getCurrLang(text['paragraph']['subText'])
, which displayed:
Argument of type 'string | Text | Language' is not assignable to parameter of type 'Text | Language'. Type 'string' is not assignable to type 'Text | Language'.
This led me to another attempt where I thought defining the key value as 'language' might help, but it did not fully address the issue:
type LangCode = 'en' | 'sv' | 'fr' | 'es';
interface Text {
[key: string]: ComponentText | Array<ComponentText>;
language?: Language;
}
type Language = {
[key in LangCode]: string;
};
Is there a more effective way to define this type of structure or any other suggestions to improve the current approach?