find the nth fibonacci number in typescript

To find the nth Fibonacci number in TypeScript, we can use recursion. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting with 0 and 1.

Here's a TypeScript function that recursively calculates the nth Fibonacci number:

index.ts
function fibonacci(n: number): number {
  if (n === 0 || n === 1) {
    return n;
  }

  return fibonacci(n - 1) + fibonacci(n - 2);
}
135 chars
8 lines

This function takes a number n as input and returns the nth Fibonacci number. If n is 0 or 1, the function simply returns n. Otherwise, it returns the sum of the previous two Fibonacci numbers, calculated by recursively calling the function with n-1 and n-2.

To test this function and find the 10th Fibonacci number, we can call it as follows:

index.ts
console.log(fibonacci(10)); // Output: 55
42 chars
2 lines

This will output 55, which is the 10th Fibonacci number.

gistlibby LogSnag