DEV Community

Acid Coder
Acid Coder

Posted on

Typescript Numeric Literal Types How To X^N (Exponentiation)

In this post, we are going to try to raise x to the power of n

x and n are both numeric literal types

to do this, we need to utilize multiplication type with a slight modification:

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 // modified
    : Multiplication<X,Y,[1,...Z],[...CreateArrayWithLengthX<X>,...V]>
Enter fullscreen mode Exit fullscreen mode

ok, we have the building block now, let's do it

type Exponentiation<X extends number, N extends number, Counter extends number[] =[], Acc extends unknown[] = [1]> =
    Counter['length'] extends N 
        ? Acc['length'] 
        : Exponentiation<X, N, [1, ...Counter], Multiplication<Acc['length'],X> >

type A = Exponentiation<2,0> // 1
type B = Exponentiation<2,1> // 2
type C = Exponentiation<2,10> // 1024
type D = Exponentiation<3,7> // 2187
type E = Exponentiation<21,3> // 9261
Enter fullscreen mode Exit fullscreen mode

playground

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

there is also some limitation to n, depending on the value of x
if x is 2, then n cannot exceed 10 (2¹⁰ is the first time exponential of 2 exceed 1000)

if x is 3, then n cannot exceed 7 (3⁷ is the first time exponential of 3 exceed 1000)

at this point, x^n is larger than 1000 and it is not possible to create an array with a length larger than 1000 for the next n because the max recursion depth is only 1000

Top comments (1)

Collapse
 
juliocastrodev profile image
juliocastrodev

This is impressive :o