[英]Enum/Type/string as keys in object Type/interface
I am trying to choose the proper typescript construct for translation objects that I use in my app.我正在尝试为我在应用程序中使用的翻译对象选择正确的 typescript 构造。 They can look like this:
它们看起来像这样:
{
'en': 'house', // English
'es': 'casa', // Spanish
'pl': 'dom', // Polish
}
In general they can have many more language codes than the above 'en', 'es', 'pl'.一般来说,它们可以有比上述'en'、'es'、'pl'更多的语言代码。 There will be around 200 in total.
总共将有200个左右。 A given translation object does not need to contain all of these keys.
给定的翻译 object 不需要包含所有这些键。
Here are my three approaches:以下是我的三种方法:
type LanguageCode = 'en' | 'es'| 'pl'
enum LanguageCode2 {
'en' = 'en',
'es' = 'es',
'pl' = 'pl',
}
type Foo = {
[key in LanguageCode]: string;
};
type Foo2 = {
[key in LanguageCode2]: string;
};
type Foo3 = {
[key in string]: string;
};
const o1: Foo = { // TS2741: property 'pl' is missing in type....
'en': 'house',
'es': 'casa',
}
const o2: Foo2 = { // TS2741: property 'pl' is missing in type....
'en': 'house',
'es': 'casa',
}
const o3: Foo3 = {
'en': 'house',
'es': 'casa',
}
The only of the objects that is transpiled correctly is o3, how can I make compile o1 and o2 correctly?唯一正确转译的对象是 o3,我怎样才能正确编译 o1 和 o2? Is there any other approach to this problem?
有没有其他方法可以解决这个问题?
type LanguageCode = "en" | "es" | "pl";
type LocalizationRecord = Partial<Record<LanguageCode, string>>;
const o1: LocalizationRecord = {
en: "house",
es: "casa",
};
const o2: LocalizationRecord = {
en: "house",
es: "casa",
};
const o3: LocalizationRecord = {
en: "house",
es: "casa",
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.