Given a number N, construct the Pascal's triangle with N rows. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll construct Pascal's triangle at the type level, producing a tuple of tuples representing N rows of the triangle using recursive type arithmetic.
Given a number N, construct the Pascal's triangle with N rows. Wikipedia
Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<Pascal<1>, [[1]]>>,
Expect<Equal<Pascal<3>, [[1], [1, 1], [1, 2, 1]]>>,
Expect<
Equal<Pascal<5>, [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]>
>,
Expect<
Equal<
Pascal<7>,
[
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
]
>
>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Length<T extends unknown[]> = T['length']
type MakeArray<N extends number, T extends 1[] = []> =
Length<T> extends N ? T : MakeArray<N, [...T, 1]>
type Add<A extends number, B extends number> =
Length<[...MakeArray<A>, ...MakeArray<B>]>
type NextRow<T extends number[], Result extends number[] = [1]> =
T extends [infer A extends number, infer B extends number, ...infer Rest extends number[]]
? NextRow<[B, ...Rest], [...Result, Add<A, B>]>
: [...Result, 1]
type Pascal<
N extends number,
Prev extends number[] = [1],
Result extends number[][] = [[1]],
> = Length<Result> extends N
? Result
: Pascal<N, NextRow<Prev>, [...Result, NextRow<Prev>]>How it works:
MakeArray converts a numeric literal into a tuple of that length, enabling type-level arithmetic.Add concatenates two such tuples and reads the resulting length to compute the sum of two numbers.NextRow takes the current row and builds the next row by sliding a window of two elements across it, summing adjacent pairs, and bookending with 1.Pascal recursively builds the triangle by accumulating rows into Result. It starts with [[1]] and repeatedly computes the next row from Prev until the result has N rows.This challenge helps you understand recursive type-level arithmetic and tuple construction, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.