问题描述
我发现当我使用泛型可变参数时,我可以成功地将函数的字符串输入强制转换为传递的文字值的联合
df_DTO2['twelve_wk_usage'] = df_DTO2[df_DTO2.twelve_wks_prior_TF == True
].groupby(['unique_id'])['sum_ni'].transform(sum))
然而,当我尝试使用普通数组作为参数提取这些类型时,我没有得到文字的联合。
declare function variadicGenericArray<Items extends string[]>(...items: Items): {[value in Items[number]: value}
const test = variadicGenericArray("One","Two");
type testType = typeof Test; // {"One": "One","Two": "Two"}
我该怎么做才能确保 declare function nonVariadicGenericArray<Items extends string[]>(items: Items): {[value in Items[number]: value}
const test = nonVariadicGenericArray(["One","Two"]);
type testType = typeof Test; // {[x: string]: string}
具有 testType
类型并且仍然让函数接受数组而不是可变参数?
一个重要的注意事项。我试图在这里编写一个函数定义,该函数应该是泛型,所以我不能只声明 {"One": "One","Two": "Two"}
或 type Values = "One" | "Two"
并使用它们,因为那么该函数将不再是通用
解决方法
玩了一会儿,看起来我可以做到这一点
declare function nonVariadicGenericArray<Items extends readonly string[]>(items: Items): {[value in Items[number]: value}
const test = nonVariadicGenericArray(["One","Two"] as const);
type testType = typeof Test; // {"One": "One","Two": "Two"}
现在我需要弄清楚哪个 API 是更好的开发者用户体验,但至少我现在有了答案。