Skip to content

Instantly share code, notes, and snippets.

@nickscript0
Created December 17, 2018 14:38
Show Gist options
  • Save nickscript0/fe188db23db8c0db3715d0b4a6242ede to your computer and use it in GitHub Desktop.
Save nickscript0/fe188db23db8c0db3715d0b4a6242ede to your computer and use it in GitHub Desktop.
Typed zip functions in TypeScript
// zip for 2 arrays
function zip2<A, B>(a: A[], b: B[]): Array<[A, B]> {
return a.map((_, c) => [a, b].map(row => row[c])) as Array<[A, B]>;
}
// zip for any number of arrays
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])));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment