代码之家  ›  专栏  ›  技术社区  ›  Nick Manning

typescript在执行操作后是否可以继续推断标记为“const”的数组的确切值?

  •  1
  • Nick Manning  · 技术社区  · 1 年前

    假设我有这个数组:

    const myArray = ["foo", 3.14, true] as const;
    

    Typescript将推断此数组为:

    readonly ["foo", 3.14, true]
    

    所以它确切地知道数组是什么。

    我正在努力增加我对typescript的了解,并试图弄清楚是否可以对这个数组执行泛型操作 as const 并保留typescript对这些值的推断。

    例如,是否可以用typescript编写一个函数 convertNumbersToStrings() 接受任何只读数组作为参数,并输出另一个只读数组,如果我将 作为常量 数组,typescript可以推断出结果是: ["foo", "3.14", true] ?

    1 回复  |  直到 1 年前
        1
  •  1
  •   motto    1 年前

    是的,这是可能的(感谢@Blackhole纠正了我周日晚上的脑功能衰竭)。

    type ConvertedNumbersToStrings<Arr extends readonly any[]> = {
        [Index in keyof Arr]:
            Arr[Index] extends number ? `${Arr[Index]}` : Arr[Index]
    }
    

    TS playground here

    映射的元组往往需要一点帮助,实现也很粗糙,但您会得到一个结果:

    function convertNumbersToStrings<Arr extends readonly any[]>(arr: Arr)
        : ConvertedNumbersToStrings<Arr>
    {
        return arr.map(x =>
            typeof x === "number" ? x.toString() : x
        ) as ConvertedNumbersToStrings<Arr>;
    }
    
    const myArray = ["foo", 3.14, true] as const;
    const out = convertNumbersToStrings(myArray);
    // typeof out = readonly ["foo", "3.14", true]
    

    在没有返回类型注释的情况下, out 的类型推断为 any[] .