DEV Community

Acid Coder
Acid Coder

Posted on • Updated on

Typescript Numeric Literal Types How To X * Y (Multiplication)

We have seen how subtraction works

now can we do multiplication?

yes we can, and this is how you do it, method 1:

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

type Multiplication<X extends number, Y extends number, Z extends number[] = []> = 
    [...CreateArrayWithLengthX<Y>]['length'] extends Z['length']
    ?[]
    :[...CreateArrayWithLengthX<X>, ...Multiplication<X,Y,[1,...Z]>]

type A = Multiplication<526,19>['length'] // 9994
type B = Multiplication<1,48>['length'] // error if 2nd interger exceed 47
Enter fullscreen mode Exit fullscreen mode

playground

method 2:

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

type Multiplication<X extends number, Y extends number, Z extends number[] = [], V extends unknown[] = []> = 
    [...CreateArrayWithLengthX<Y>]['length'] extends Z['length']
    ? V['length']
    : Multiplication<X,Y,[1,...Z],[...CreateArrayWithLengthX<X>,...V]>

type A= Multiplication<19,526> // 9994
type B= Multiplication<526,19> // 9994
Enter fullscreen mode Exit fullscreen mode

limitation: the product cannot exceed 9999 because the max tuple size is 9999

playground

2nd method is better because the 1st method 2nd integer cannot be larger than 47 (method 1 Multiplication is not tail recursion, but still I was expecting it to error at 50, not 48, hmm...)

Top comments (0)