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.
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 trueGood Luck!
Change the following code to make the test cases pass (no type check errors).
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:
LengthCompare checks if one number has more digits than the other -- a longer number is always greater (for non-negative integers).CompareDigits iterates through each digit pair from left to right.DigitGreater determines which of two single digits is larger by checking their relative positions in the string '0123456789'.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.
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