In nextjs, I’m using this example to load translations and return them into the component
import "server-only";
import i18nConfig from "../../i18n-config";
const dictionaries = {
en: () =>
import("../../dictionaries/en.json").then((module) => module.default),
hr: () =>
import("../../dictionaries/hr.json").then((module) => module.default),
};
type TDictionary = (typeof dictionaries)["en"];
export const getDictionary = async (locale: string): Promise<TDictionary> =>
dictionaries[
i18nConfig.locales.includes(locale) ? locale : i18nConfig.defaultLocale
]();
export default async function Navbar ( props: ILangParams ) {
const dict = await getDictionary(props.params.lang);
return (
<nav className={styles.navbar}>
<Link href="/" className={styles.linkLogo}>
<Image
priority
src={logo}
alt={dict.navbar.links.home}
className={styles.logo}
/>
</nav>
);
}
If I don’t type getDictionary to return Promise<TDictionary>
, it returns as Promise<any>
.
With Promise<TDictionary>
, it returns
const dict: () => Promise<{
navbar: {
links: {
logoAlt: string;
escapeGames: string;
becomeAPartner: string;
bookDemo: string;
};
};
}>
This seems wrong as I cannot use dict.navbar.links.home to get the translated string.
How do I properly type this?
the structure is the same for all translations