Typescript Numeric Literal Types X-Y (Subtraction)

Acid Coder
Jun 30, 2022

--

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
? ACC
: 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

playground

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

--

--

Acid Coder

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