DEV Community

Acid Coder
Acid Coder

Posted on

4 3

Typescript Numeric Literal Types How To Y / X (Division)

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

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

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