I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals.
First, I created the BuildArray
type:
type BuildArray<
Length extends number,
Ele = unknown,
Arr extends unknown[] = []
> = Arr['length'] extends Length
? Arr
: BuildArray<Length, Ele, [...Arr, Ele]>;
type MyArray = BuildArray<3> // type MyArray = [unknown, unknown, unknown]
Next, I implemented the Add
type:
type Add<Num1 extends number, Num2 extends number> =
[...BuildArray<Num1>, ...BuildArray<Num2>]['length']
type AddResult = Add<2, 5> // type AddResult = 7
However, when trying to create a Multiply
type based on Add
, I encountered an error:
type Multiply<Num1 extends number, Num2 extends number, Counter extends number = 0, Result extends number = 0> =
Counter extends Num2?
Result:
Multiply<Num1, Num2, Add<Counter, 1>, Add<Num1, Result>>
type MultiplyResult = Multiply<4, 5> // type MultiplyResult = 20
While the result is correct, there was a compilation error:
https://i.sstatic.net/dYoc4.png
Can anyone explain why this compilation error is happening?