【发布时间】:2021-04-29 19:37:02
【问题描述】:
我发现当我使用泛型可变参数时,我可以成功地将函数的字符串输入强制转换为所传递的文字值的联合
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"} 类型并且仍然让函数接受数组而不是可变参数?
重要说明。我正在尝试在这里编写一个函数定义,并且该函数应该是 generic,所以我不能只声明 type Values = "One" | "Two" 或 type Values = ["One", "Two"] as const 并使用它们,因为那时函数会不再是通用
【问题讨论】:
标签: typescript generics variadic