Examining the example below:
export type AppMessages = Awaited<ReturnType<typeof loadMessages>>;
export type Locale = "en" | "fr" | "es";
export const loadMessages = async (locale: Locale) => ({
foo: locale === 'en'
? (await import('../../messages/en/foo.json')).default
: (await import(`../../messages/${locale}/foo.json`)).default
});
All JSON files have a consistent structure, but the AppMessages
type is resolved as
type AppMessages = {
foo: any;
}
A potential solution proposed is:
export type AppMessages = Awaited<ReturnType<typeof loadDefaultMessages>>;
export type Locale = "en" | "fr" | "es";
const loadDefaultMessages = async () => ({
foo: (await import("../../messages/en/foo.json")).default,
});
const loadLocaleMessages = async (locale: Locale): Promise<AppMessages> => ({
foo: (await import(`../../messages/${locale}/foo.json`)).default,
});
export const loadMessages = async (locale: AppLanguages) =>
locale === "en"
? await loadDefaultMessages()
: await loadLocaleMessages(locale);
The above solution shapes the AppMessages
type correctly, but it may lead to repetition and possible code duplication.
Is there a more efficient approach that achieves the same outcome of having AppMessages
shaped based on the JSON data files? Setting the AppMessages
type manually is not an option.