DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

3 2

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...)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay