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

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]>
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Acid Coder

Typescript Zombie. Youtube Pikachu On Acid.