Given a number N, find the Nth triangular number, i.e. `1 + 2 + 3 + ... + N` Learn tuple manipulation, array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Triangular type that computes the Nth triangular number (the sum 1 + 2 + 3 + ... + N) entirely at the type level using tuple length arithmetic.
Given a number N, find the Nth triangular number, i.e. 1 + 2 + 3 + ... + N
Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<Triangular<0>, 0>>,
Expect<Equal<Triangular<1>, 1>>,
Expect<Equal<Triangular<3>, 6>>,
Expect<Equal<Triangular<10>, 55>>,
Expect<Equal<Triangular<20>, 210>>,
Expect<Equal<Triangular<55>, 1540>>,
Expect<Equal<Triangular<100>, 5050>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Triangular<
N extends number,
Counter extends any[] = [],
Acc extends any[] = []
> = Counter['length'] extends N
? Acc['length']
: Triangular<N, [...Counter, 0], [...Acc, ...Counter, 0]>;How it works:
Counter tracks the current step (from 0 up to N), and Acc accumulates the total sum as a tuple whose length represents the resultCounter grows by one element (incrementing the step), and Acc grows by the current step's value plus one, achieved by spreading [...Acc, ...Counter, 0] -- this adds Counter['length'] + 1 elements to AccCounter['length'] equals N, the recursion stops and returns Acc['length'] as the computed triangular numberThis challenge helps you understand type-level arithmetic through tuple length manipulation and how to apply recursive accumulation patterns in real-world scenarios.
This challenge is originally from here.