将通用字符串数组转换为字符串文字的并集

问题描述

我发现当我使用泛型可变参数时,我可以成功地将函数的字符串输入强制转换为传递的文字值的联合

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 是更好的开发者用户体验,但至少我现在有了答案。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...