Hone logo
Hone
Problems

Type-Level Fibonacci Sequence Generation in TypeScript

This challenge focuses on harnessing TypeScript's powerful type system to compute the Fibonacci sequence at compile time. Unlike runtime calculations, type-level computation allows for verifying complex logic and generating types that represent data structures or configurations derived from such computations. Mastering this technique can unlock advanced type safety and sophisticated metaprogramming capabilities in your TypeScript projects.

Problem Description

Your task is to implement a TypeScript type that can calculate the nth number in the Fibonacci sequence. The Fibonacci sequence is defined by the recurrence relation: F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) for n > 1

You need to create a generic type Fibonacci<N> where N is a positive integer represented as a TypeScript number literal. This type should resolve to a number literal representing the nth Fibonacci number.

Key Requirements:

  • The type must correctly compute Fibonacci numbers for any non-negative integer N.
  • The solution should be purely at the type level, meaning no runtime JavaScript code should be executed to compute the Fibonacci numbers.
  • The implementation should be efficient enough to be practical for reasonable values of N (e.g., up to 30-40).

Expected Behavior: Fibonacci<0> should resolve to 0. Fibonacci<1> should resolve to 1. Fibonacci<2> should resolve to 1. Fibonacci<3> should resolve to 2. Fibonacci<10> should resolve to 55.

Edge Cases to Consider:

  • N = 0 and N = 1 are the base cases and must be handled correctly.

Examples

Example 1:

// Input type:
type Result1 = Fibonacci<5>;

// Expected Output Type:
// Result1 will resolve to the type `5` (since F(5) = F(4) + F(3) = 3 + 2 = 5)

Explanation: F(0)=0, F(1)=1, F(2)=1, F(3)=2, F(4)=3, F(5)=5.

Example 2:

// Input type:
type Result2 = Fibonacci<10>;

// Expected Output Type:
// Result2 will resolve to the type `55`

Explanation: F(10) is calculated by repeatedly applying the Fibonacci rule.

Example 3:

// Input type:
type Result3 = Fibonacci<0>;

// Expected Output Type:
// Result3 will resolve to the type `0`

Explanation: This tests the base case for N = 0.

Constraints

  • N will be a non-negative integer literal (0 or greater).
  • The solution must be implemented using TypeScript's conditional types, recursive types, and potentially template literal types or other advanced type features.
  • Avoid external libraries or runtime code.

Notes

This problem requires a recursive approach at the type level. Think about how you can represent the base cases and the recursive step using TypeScript's conditional types. You might find it helpful to use an "infer" keyword within your conditional types to destructure or access parts of other types. Consider how you can represent the subtraction of numbers at the type level if needed, or if there are existing patterns to leverage.

Loading editor...
typescript