I have a background in python, and I enjoy playing with functional languages, and I'm learning typescript, so I'd like to have a zip()
function that works somewhat like Python's. I see the typescript has gained both generators and variadic generics, so I think this should be possible. I have something that is very close to what I want, but it's not quite. I'm sure I'm either doing something obvious, or I'm about to learn the deep workings of the typescript type system.
What I want is a function that takes a variable number of arrays, and yields a tuple of elements from those arrays until the shortest array is exhausted. I wrote a generator that does that, but I'm having trouble getting the typing right.
function* zip<T extends any[]>(...args: T) {
for (let i = 0; i < Math.min(...args.map((e) => { return e.length })); ++i) {
yield args.map((e) => { return e[i]; }) as T;
}
}
If I remove the as T
then the function works, but I lose all type information, if not then I get A return type [...T[]]
, but I want [...T]
.
For example, zip([1, 2, 3], ['a', 'b', 'c'])
, should have a return type of [number, string]
, but it has [number[], string[]]