I’m trying to make a generic interface to define a translation dictionary where the primary keys specify the language, and within each language the same keys are present.
Here’s my attempt so far using generics (preferable):
interface TranslationDict<K extends string, O extends K[number]> {
eng: Record<K, string>;
jpn: Record<O, string>;
}
const translationDict: TranslationDict<string, string> = {
eng: {
year: "year",
month: "month",
day: "day",
file: "file",
},
jpn: {
year: "年",
month: "月",
day: "日",
file: "ファイル",
file2: "bla", // I want this to throw a type error
},
};
Without generics, this works, but seems like way too much boilerplate:
const cols = ["year", "month", "day", "file"] as const;
export const commonCols: {
eng: Record<(typeof cols)[number], string>;
jpn: Record<(typeof cols)[number], string>;
} = {
eng: {
year: "year",
month: "month",
day: "day",
file: "file",
},
jpn: {
year: "年",
month: "月",
day: "日",
file: "ファイル",
file2: "bla", // TYPE ERROR
},
};
How do I use generics to constrain the keys of jpn
to be the same as the keys of eng
?