DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

Typescript Numeric Literal Types How To X + Y (Summation)

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
Enter fullscreen mode Exit fullscreen mode

playground

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

looking for

Top comments (0)