#2257Medium

MinusOne

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.

Challenge Instructions: MinusOne

Medium

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> // 54

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

Loading...

Detailed Explanation

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:

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

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