Skip to content Skip to sidebar Skip to footer

Possible To Use Array.prototype.map() On Tuple In TypeScript While Preserving Tuple Length In Return Type?

I was hoping that if I use the built-in map function on a tuple of length N in TypeScript then the return type would also be a tuple of length N (perhaps with different type for th

Solution 1:

Please try next:


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")[]

I believe this is not the best solution, because you still have ('3'|'2'|'1')[] and not ['1','2','3'], but this is some kind of step forward

I will happy to see other solutions here. Very interesting problem )

Works only with T.S 4.1

UPDATE

There is a possibility to create type what you want with some help of overloading and 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 }));

Playground


Post a Comment for "Possible To Use Array.prototype.map() On Tuple In TypeScript While Preserving Tuple Length In Return Type?"