Код в этой статье и реализация Ziplongest находятся в эта суть .
Встроенный Zip
Функция повсеместна в Python. Это позволяет итерации с очень читаемой итерацией по нескольким итерам:
def naturals(): n = 1 while True: yield n n += 1 for n, c in zip(naturals(), "Hello!"): print(n, c) # 1 H # 2 e # 3 l # 4 l # 5 o # 6 !
Теперь с Намеченные типы в TypeScript , мы можем сделать то же самое, и все же сохранив наши прекрасные типы!
С на карту типам мы можем сделать Iterableify
Тип, который займет тип, и изменить его так, чтобы его участники были иерными типа:
type Iterableify= { [K in keyof T]: Iterable }
Например
type T1 = Iterableify// Iterable [] type T2 = Iterableify<{a: number, b: string}> // {a: Iterable , b: Iterable } type T3 = Iterableify<[number, string][]> // Iterable<[number, string]>[]
Затем мы можем сделать простую функцию Zip таким образом:
function* zip>( ...toZip: Iterableify ): Generator { // Get iterators for all of the iterables. const iterators = toZip.map(i => i[Symbol.iterator]()) while (true) { // Advance all of the iterators. const results = iterators.map(i => i.next()) // If any of the iterators are done, we should stop. if (results.some(({ done }) => done)) { break } // We can assert the yield type, since we know none // of the iterators are done. yield results.map(({ value }) => value) as T } }
Поскольку нанесенные на карту типы также влияют на кортежи TypeScript, теперь мы можем сделать что -то вроде этого:
for (const [a, b] of zip([1, 2, 3], "abc")) { // type of a is number! // type of b is string! // This has no compilation errors! console.log(b.repeat(a)) }
Оригинал: “https://dev.to/chrismilson/zip-iterator-in-typescript-ldm”