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.ts135 chars8 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.ts42 chars2 lines
This will output 55
, which is the 10th Fibonacci number.
gistlibby LogSnag