#4182Medium

Fibonacci Sequence

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.

Challenge Instructions: Fibonacci Sequence

Medium

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> // 21

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

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:

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

Share this challenge

Learn the Concepts

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount