Created
December 17, 2018 14:38
-
-
Save nickscript0/fe188db23db8c0db3715d0b4a6242ede to your computer and use it in GitHub Desktop.
Typed zip functions in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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