Given a number (always positive) as a type. Your type should return the number decreased by one. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement MinusOne<T>, a type that takes a positive number literal type and returns the number decreased by one, handling values up to very large numbers.
Given a number (always positive) as a type. Your type should return the number decreased by one.
For example:
type Zero = MinusOne<1> // 0
type FiftyFour = MinusOne<55> // 54Change the following code to make the test cases pass (no type check errors).
type ParseInt<T extends string> =
T extends `${infer N extends number}` ? N : never;
type ReverseString<S extends string> =
S extends `${infer First}${infer Rest}`
? `${ReverseString<Rest>}${First}`
: '';
type SubOneMap = {
'0': '9';
'1': '0';
'2': '1';
'3': '2';
'4': '3';
'5': '4';
'6': '5';
'7': '6';
'8': '7';
'9': '8';
};
type RemoveLeadingZeros<S extends string> =
S extends `0${infer Rest}`
? Rest extends ''
? '0'
: RemoveLeadingZeros<Rest>
: S;
type SubOneReversed<S extends string> =
S extends `${infer D extends keyof SubOneMap}${infer Rest}`
? D extends '0'
? `9${SubOneReversed<Rest>}`
: `${SubOneMap[D]}${Rest}`
: '';
type MinusOne<T extends number> =
ParseInt<RemoveLeadingZeros<ReverseString<SubOneReversed<ReverseString<`${T}`>>>>>;How it works:
ReverseString reverses the digits so we can process from the least significant digit (ones place) firstSubOneReversed works on the reversed string: if the current digit is '0', it becomes '9' and the borrow carries to the next digit (recursion continues); otherwise, it decrements the digit using SubOneMap and keeps the remaining digits unchangedRemoveLeadingZeros strips any leading zeros that result from subtraction (e.g., 100 - 1 = 099 becomes 99), while preserving a single '0' for the result of 1 - 1ParseInt converts the final string back into a number literal type using template literal inference with infer N extends number9_007_199_254_740_992This challenge helps you understand type-level arithmetic via string manipulation, and how to apply these concepts 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