如何解决将通用字符串数组转换为字符串文字的并集
我发现当我使用泛型可变参数时,我可以成功地将函数的字符串输入强制转换为传递的文字值的联合
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 是更好的开发者用户体验,但至少我现在有了答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。