Implement a generic `Fibonacci<T>` that takes a number `T` and returns its corresponding [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number). Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a generic Fibonacci<T> that takes a number T and returns its corresponding Fibonacci number. The sequence starts 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.
Implement a generic Fibonacci<T> that takes a number T and returns its corresponding Fibonacci number.
The sequence starts: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
For example
type Result1 = Fibonacci<3> // 2
type Result2 = Fibonacci<8> // 21Change the following code to make the test cases pass (no type check errors).
Since TypeScript's type system doesn't support arithmetic, we simulate addition and counting using tuple lengths. We track the current position, the previous two Fibonacci values (as tuples whose lengths represent the numbers), and recurse until we reach position T.
type Fibonacci<
T extends number,
CurrentIndex extends readonly number[] = [1],
Prev extends readonly number[] = [],
Current extends readonly number[] = [1]
> = CurrentIndex['length'] extends T
? Current['length']
: Fibonacci<T, [...CurrentIndex, 1], Current, [...Prev, ...Current]>How it works:
CurrentIndex is a tuple that grows by one element each step, tracking our position in the sequencePrev holds a tuple whose length is the (n-1)th Fibonacci numberCurrent holds a tuple whose length is the nth Fibonacci numberCurrentIndex['length'] equals T, we return Current['length'] as the resultPrev becomes Current, and the new Current becomes [...Prev, ...Current], which simulates addition via tuple concatenationThis challenge helps you understand recursive type computation using tuple length arithmetic and how to apply this concept 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