You don't need variadic tuple types for this. The problem is that the TypeScript standard library definition for Array.prototype.map()
doesn't attempt to represent the fact that array length is preserved. There is an open issue, microsoft/TypeScript#29841, asking for this to be addressed.
If you need the compiler to pay attention to length, you will need to use your own typing for map()
via, say, declaration merging. Possibly something like this:
interface Array<T> {
map<U>(
callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any
): { [K in keyof this]: U };
}
I'm using mapped tuple types to represent the length preservation, and specifically polymorphic this
to capture the fact that we want to iterate over the keys of whatever subtype of Array<T>
we happen to be using, such as a tuple.
But messing with definitions for such commonly-used methods might have unexpected results in other parts of your code base, so unless you'd like to worry about whether every use of map()
should behave this way, you can use a type assertion to tell the compiler that the result of this specific call to map()
is of a particular length and type:
const variadicMapping = <T extends T1[]>(objects: T) => {
return objects.map((e) => transformType(e)) as { [K in keyof T]: T2 };
};
Either way you should get the behavior you want:
const bar = variadicMapping(foo); // [T2, T2]
Playground link to code