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

Acid Coder
Jun 29, 2022

--

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Acid Coder
Acid Coder

Written by Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

No responses yet

Write a response