#27152Medium

Triangular number

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.

Challenge Instructions: Triangular number

Medium

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

ChallengeSolution
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>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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:

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

Share this challenge