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 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount