请尝试下一步:
type A = readonly [1, 2, 3]
const nums: A = [1, 2, 3];
const toStr = <T extends number>(num: T) => num.toString() as `${T}`
const result2 = nums.map(toStr); // ("3" | "1" | "2")[]
我相信这不是最好的解决方案,因为你仍然有 ('3'|'2'|'1')[] 而不是 ['1','2','3'],但这是某种向前一步
我很高兴在这里看到其他解决方案。很有趣的问题)
仅适用于 T.S 4.1
UPDATE
在以下的帮助下可以创建您想要的类型超载 https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads and 可变元组类型 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types
type Json =
| string
| number
| boolean
| { [prop: string]: Json }
| Array<Json>
type CustomMap<T extends ReadonlyArray<Json>> = {
[Index in keyof T]: { elem: T[Index] }
}
function map<Elem extends Json, List extends Elem[], Return>(list: [...List], callback: (value: Elem) => Return): CustomMap<List>
function map<Elem extends Json>(list: Elem[], callback: (elem: Elem) => unknown) {
return list.map(callback)
}
// const result2: [{
// elem: 1;
// }, {
// elem: 2;
// }, {
// elem: 3;
// }]
const result2 = map([1, 2, 3], elem => ({ elem }));
操场 https://tsplay.dev/mqQDkm