Typescript Two Numeric Literal Types How To X - Y (Subtraction)

tylim88

Acid Coder

Posted on June 30, 2022

Typescript Two Numeric Literal Types How To 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
    ? 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
Enter fullscreen mode Exit fullscreen mode

playground

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

💖 💪 🙅 🚩
tylim88
Acid Coder

Posted on June 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related