Implement `CompareArrayLength` to compare two array length(T & U). Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement CompareArrayLength<T, U> which compares the lengths of two arrays, returning 1 if T is longer, -1 if U is longer, and 0 if they are equal.
Implement CompareArrayLength to compare two array length(T & U).
If length of T array is greater than U, return 1; If length of U array is greater than T, return -1; If length of T array is equal to U, return 0.
Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<CompareArrayLength<[1, 2, 3, 4], [5, 6]>, 1>>,
Expect<Equal<CompareArrayLength<[1, 2], [3, 4, 5, 6]>, -1>>,
Expect<Equal<CompareArrayLength<[], []>, 0>>,
Expect<Equal<CompareArrayLength<[1, 2, 3], [4, 5, 6]>, 0>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type CompareArrayLength<T extends any[], U extends any[]> =
T extends [any, ...infer TRest]
? U extends [any, ...infer URest]
? CompareArrayLength<TRest, URest>
: 1
: U extends [any, ...any[]]
? -1
: 0How it works:
T extends [any, ...infer TRest] checks if T still has elements; if so, we also check UCompareArrayLength<TRest, URest> to compare the remaining portions1U extends [any, ...any[]]), U is longer so we return -10This challenge helps you understand recursive tuple deconstruction for comparing structural properties of arrays and how to apply this concept in real-world scenarios.
This challenge is originally from here.