Behold the incredible code I have:
export type Locale = "en" | "fr";
export type Namespace = "products" | "home";
const dict = {
en: {
home: { title: "My Super Title" },
products: { product: "Product" },
},
fr: {
home: { title: "Mon Super Titre" },
products: { product: "Produit" },
},
};
export const getTranslation = (namespace: Namespace, locale: Locale) => {
return dict[locale][namespace];
};
const t = await getTranslation("home", "en");
// Typescript infer of T
// const t: {
// title: string;
// } | {
// product: string;
// } | {
// title: string;
// } | {
// product: string;
// }
I assumed TypeScript would correctly infer this, but unfortunately, that is not the case.
So my initial query is, why is TypeScript unable to infer this accurately?
Is there a way I can assist by manually typing getTranslation
to ensure proper inference?
I was initially anticipating:
{
title: string;
}
By the way, my TypeScript version is "^5"
Perhaps I am not utilizing the correct keyword to uncover the solution.
Nevertheless, I am firmly convinced that there exists a type solution to resolve my dilemma.