Zip
介绍
实现类型Zip<T, U>
, T和U必须是元组.
ts
type exp = Zip<[1, 2], [true, false]> // expected to be [[1, true], [2, false]]
View on GitHubts
type exp = Zip<[1, 2], [true, false]> // expected to be [[1, true], [2, false]]
起点
ts
/* _____________ Your Code Here _____________ */typeZip <T ,U > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[], []>, []>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[1, 2], [true, false]>, [[1, true], [2, false]]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[1, 2, 3], ['1', '2']>, [[1, '1'], [2, '2']]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[], [1, 2, 3]>, []>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[[1, 2]], [3]>, [[[1, 2], 3]]>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeZip <T ,U > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[], []>, []>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[1, 2], [true, false]>, [[1, true], [2, false]]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[1, 2, 3], ['1', '2']>, [[1, '1'], [2, '2']]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[], [1, 2, 3]>, []>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Zip <[[1, 2]], [3]>, [[[1, 2], 3]]>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// most populartypeZip <A extends any[],B extends any[],L extends any[] = []> =L ['length'] extendsA ['length'] |B ['length']?L :Zip <A ,B , [...L , [A [L ['length']],B [L ['length']]]]>
ts
// most populartypeZip <A extends any[],B extends any[],L extends any[] = []> =L ['length'] extendsA ['length'] |B ['length']?L :Zip <A ,B , [...L , [A [L ['length']],B [L ['length']]]]>
ts
// my solutiontypeZip <T extends any[],U extends any[],A extends any[] = []> =T extends [inferF , ...inferR ]?U extends [inferF2 , ...inferR2 ]?Zip <R ,R2 , [...A , [F ,F2 ]]>:Zip <R , [], [...A ]>:A ;
ts
// my solutiontypeZip <T extends any[],U extends any[],A extends any[] = []> =T extends [inferF , ...inferR ]?U extends [inferF2 , ...inferR2 ]?Zip <R ,R2 , [...A , [F ,F2 ]]>:Zip <R , [], [...A ]>:A ;