#34007Medium

Compare Array Length

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.

Challenge Instructions: Compare Array Length

Medium

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).

ChallengeSolution
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>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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
      : 0

How it works:

This 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.

Share this challenge