type-challenges:Zip

31 阅读1分钟

Zip

问题描述

在这个挑战中,你应该实现一个类型 Zip<T, U>,T 和 U 必须是Tuple

type exp = Zip<[1, 2], [true, false]> // expected to be [[1, true], [2, false]]
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'type cases = [
  Expect<Equal<Zip<[], []>, []>>,
  Expect<Equal<Zip<[1, 2], [true, false]>, [[1, true], [2, false]]>>,
  Expect<Equal<Zip<[1, 2, 3], ['1', '2']>, [[1, '1'], [2, '2']]>>,
  Expect<Equal<Zip<[], [1, 2, 3]>, []>>,
  Expect<Equal<Zip<[[1, 2]], [3]>, [[[1, 2], 3]]>>,
]
​
​
// ============= Your Code Here =============
// 答案1
type Zip<A extends any[], B extends any[], L extends any[] = []> = L['length'] extends A['length'] | B['length']
  ? L
  : Zip<A, B, [...L, [A[L['length']], B[L['length']]]]>
    
// 答案2
type Zip<T extends readonly any[], U extends readonly any[], R extends any[] = []> = T extends [infer R1, ...infer R2]
  ? U extends [infer R3, ...infer R4]
    ? Zip<R2, R4, [...R, [R1, R3]]>
    : R
  : R
​