Typescript Numeric Literal Types X-Y (Subtraction)

We have seen how can we add two numeric literals type

now can we apply similar tricks for subtraction?

yes we can, this is how we do it:

type CreateArrayWithLengthX<
LENGTH extends number,
ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
: CreateArrayWithLengthX<LENGTH, [...ACC,1]>

type Subtraction<LARGER extends number, SMALLER extends number, GAP extends number[] = []> =
[...GAP,...CreateArrayWithLengthX<SMALLER>]['length'] extends [...CreateArrayWithLengthX<LARGER>]['length']
? GAP['length']
: Subtraction<LARGER, SMALLER, [1,...GAP]>

type result = Subtraction<849, 654> // 195


limitation: the number cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)