Acid Coder

In the last post we know multiplication is possible

In this post we are going to try division

type CreateArrayWithLengthX<
LENGTH extends number,
ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
? ACC
: CreateArrayWithLengthX<LENGTH, [...ACC,1]>
type Division<Dividend extends number, Divisor extends number, ACC extends unknown[] = [], Counter extends unknown[] = []> =
[...ACC,...CreateArrayWithLengthX<Divisor>]['length'] extends [...CreateArrayWithLengthX<Dividend>]['length']
? [1,...Counter]['length']
: Division<Dividend, Divisor, [...ACC,...CreateArrayWithLengthX<Divisor>],[1,...Counter]>
type result = Division<999, 3> // 333

playground

limitation: the dividend cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer. the divisor must be factors of the dividend

--

--

We have seen how can we add two numeric literals type

now can we apply similar tricks for subtraction?

yes we can, this is how we do it:

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

type Subtraction<LARGER extends number, SMALLER extends number, GAP extends number[] = []> =
[...GAP,...CreateArrayWithLengthX<SMALLER>]['length'] extends [...CreateArrayWithLengthX<LARGER>]['length']
? GAP['length']
: Subtraction<LARGER, SMALLER, [1,...GAP]>

type result = Subtraction<849, 654> // 195

playground

limitation: the number cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer

--

--

here is how you do it

type TupleToArray<
T extends unknown[],
Acc = never
> = T extends [infer H, ...infer Rest]
? Rest extends []
? (H | Acc)[]
: TupleToArray<Rest, Acc | H>
: "impossible route"
type A = TupleToArray<[number, string, boolean]> // (string | number | boolean)[]

playground

joke, I was messing, here is the easy way

type B = [number, string, boolean][number][] // (string | number | boolean)[]

--

--

Have you ever wondered how to add 2 numeric literal types?

now you know

type CreateArrayWithLengthX<
LENGTH extends number,
ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
? ACC
: CreateArrayWithLengthX<LENGTH, [...ACC,1]>
type AddTwoNumber<T extends number, U extends number> = [...CreateArrayWithLengthX<T>,...CreateArrayWithLengthX<U>]['length']type A = AddTwoNumber<999,999> //1998

playground

limitation: the number cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer

--

--