DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

4 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay