DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

3 1

Typescript Two Numeric Literal Types How To X - Y (Subtraction)

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
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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

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

Okay