是的,这是可能的(感谢@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[]
.