【问题标题】:Turning a generic string array into a union of string literals将通用字符串数组转换为字符串文字的并集
【发布时间】: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


    【解决方案1】:

    玩了一会儿,看起来我可以做到这一点

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

    【讨论】:

      猜你喜欢
      • 2011-06-18
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多