我得到了这个超级代码。
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;
// }
我认为打字稿能够正确推断这一点,但事实并非如此。 所以我的第一个问题是,为什么打字稿无法正确推断这一点? 我还可以通过在 getTranslation 中添加手动输入来帮助他,以便他可以正确推断。 我被期待了
{
title: string;
}
顺便说一句,我正在使用打字稿“^5”
也许我只是没有使用正确的关键字来找到解决方案。
但我 100% 确定可以通过打字来解决我的问题。
您可以简单地使用泛型类型参数:
export const getTranslation = <N extends Namespace, L extends Locale>(namespace: N, locale: L) => {
return dict[locale][namespace];
};