You can already define a typed zip function that accepts a fixed number of parameters as follows:
function zip2<A, B>(a: A[], b: B[]): Array<[A, B]>
I'm wondering if it is now possible to create a zip function that accepts rest parameters with a generic return type?
function zip(...args) {
return args[0].map((_, c) => args.map(row => row[c]));
}
As far as I can tell the new generic rest parameters added in Typescript 3.0 <T extends any[]>
is still not enough to type the previous function?
In typescript@next
(to be released as TypeScript 3.1) with mapped tuples:
type Zip<T extends unknown[][]> = { [I in keyof T]: T[I] extends (infer U)[] ? U : never }[];
function zip<T extends unknown[][]>(...args: T): Zip<T> {
return <Zip<T>><unknown>(args[0].map((_, c) => args.map(row => row[c])));
}
declare const y: number[], z: string[];
let yz = zip(y, z); // [number, string][]
🌹 (Had to tease Basarat. 😊)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With