Within my Next.js project, I have implemented a method for loading translations and passing them into the component. Here is an example:
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 specify that getDictionary should return Promise<TDictionary>
, it defaults to Promise<any>
.
By using Promise<TDictionary>
, the returned structure looks like this:
const dict: () => Promise<{
navbar: {
links: {
logoAlt: string;
escapeGames: string;
becomeAPartner: string;
bookDemo: string;
};
};
}>
This causes issues as I am unable to access the translated strings using dict.navbar.links.home.
How can I correctly type this in order to utilize the translation keys?
The structure remains consistent across all translations, requiring only one cast ((typeof dictionaries)["en"]).