Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a typed zip function be implemented now with Typescript 3.0's generic rest parameters?

Tags:

typescript

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?

like image 671
Nick Avatar asked Jan 01 '23 23:01

Nick


1 Answers

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. 😊)

like image 90
Matt McCutchen Avatar answered May 27 '23 19:05

Matt McCutchen