Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: is there a way to create a utility type to do minus calculation on numbers?

Tags:

typescript

I made a utility type to add two number type

type createArray<Len, Ele, Arr extends Ele[] = []> =  Arr['length'] extends Len ? Arr : createArray<Len, Ele, [Ele, ...Arr]>

type Add<A extends number, B extends number> = [...createArray<A, 1>, ...createArray<B, 1>]['length']

so that Add<1,2> gives you 3 of the number type. However I was struggling to implement the Minus utility type to achieve the minus calculation

ideally Minus<3,1> would give you 2.

like image 560
Joji Avatar asked Nov 03 '25 17:11

Joji


1 Answers

You can implement Minus in a similar way to how you implemented Add: by variadic tuple manipulation with your CreateArray type function:

type Minus<A extends number, B extends number> =
    CreateArray<A, 1> extends [...CreateArray<B, 1>, ...infer R] ? R['length'] : never;

Here we are creating two tuples of length A and B. If A is greater than or equal to B, then CreateArray<A, 1> will start with at least the same elements from CreateArray<B, 1>. By doing conditional type inference on the rest of the elements from CreateArray<A, 1>, we get a tuple R whose length is B minus A:

type Seven = Minus<10, 3> // 7
type Two = Minus<3, 1> // 2

Please note that there are definitely caveats here, and they're the same as in Add; if your A or B are negative, or not whole numbers, or too large in magnitude (bigger than 999), you will run into compiler problems. So be careful; this sort of code is for pleasure, not business.

Playground link to code

like image 138
jcalz Avatar answered Nov 05 '25 06:11

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!