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 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount