#4425Medium

Greater Than

In This Challenge, You should implement a type `GreaterThan<T, U>` like `T > U` Learn array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a GreaterThan<T, U> type that compares two non-negative numbers at the type level, returning true when T is strictly greater than U.

Challenge Instructions: Greater Than

Medium

In This Challenge, You should implement a type GreaterThan<T, U> like T > U

Negative numbers do not need to be considered.

For example

GreaterThan<2, 1> //should be true
GreaterThan<1, 1> //should be false
GreaterThan<10, 100> //should be false
GreaterThan<111, 11> //should be true

Good Luck!

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

type NumberToTuple<T extends string, Result extends unknown[] = []> =
  T extends `${infer First}${infer Rest}`
    ? NumberToTuple<Rest, [...{ [K in keyof Result]: [...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[], ...Result[K] & unknown[]] }[number] extends never ? [] : never, /* complex */ ]>
    : Result;

A simpler and more readable approach uses digit-by-digit string comparison:

type GreaterThan<T extends number, U extends number> =
  `${T}` extends `${U}` ? false : GreaterThanStr<`${T}`, `${U}`>;
 
type DigitGreater<A extends string, B extends string> =
  '0123456789' extends `${string}${A}${string}${B}${string}` ? false :
  A extends B ? false : true;
 
type CompareDigits<A extends string, B extends string, Result extends boolean = false> =
  A extends `${infer AF}${infer AR}`
    ? B extends `${infer BF}${infer BR}`
      ? AF extends BF
        ? CompareDigits<AR, BR, Result>
        : CompareDigits<AR, BR, DigitGreater<AF, BF>>
      : true
    : B extends `${string}${string}`
      ? false
      : Result;
 
type GreaterThanStr<A extends string, B extends string> =
  LengthCompare<A, B> extends 'greater' ? true :
  LengthCompare<A, B> extends 'less' ? false :
  CompareDigits<A, B>;
 
type LengthCompare<A extends string, B extends string> =
  A extends `${infer _}${infer AR}`
    ? B extends `${infer _}${infer BR}`
      ? LengthCompare<AR, BR>
      : 'greater'
    : B extends '' ? 'equal' : 'less';

How it works:

This challenge helps you understand type-level arithmetic and string manipulation techniques, and how to apply them in real-world scenarios.

This challenge is originally from here.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount