TypeScript Tutorial: Creating a Simple Interactive Number Fact Finder

Have you ever been fascinated by numbers? Do you find yourself pondering their properties, relationships, and the patterns they form? Numbers are more than just quantities; they hold secrets, interesting facts, and surprising connections. In this tutorial, we’ll embark on a journey into the world of numbers using TypeScript, a powerful and popular programming language that adds static typing to JavaScript. We’ll create a simple, interactive “Number Fact Finder” application that allows users to input a number and discover interesting facts about it. This project is a fantastic way to learn TypeScript fundamentals while exploring the intriguing realm of mathematics.

Why TypeScript?

Before we dive into the code, let’s briefly discuss why TypeScript is an excellent choice for this project and, more broadly, for web development. TypeScript offers several advantages over plain JavaScript:

  • Static Typing: TypeScript allows you to define the types of variables, function parameters, and return values. This helps catch errors early in the development process, improving code quality and reducing debugging time.
  • Code Completion and Refactoring: TypeScript provides excellent code completion and refactoring support in most code editors, making it easier to write and maintain your code.
  • Object-Oriented Programming (OOP): TypeScript supports OOP principles like classes, interfaces, and inheritance, enabling you to write more organized and maintainable code.
  • Scalability: TypeScript’s features make it easier to manage large and complex projects.
  • Improved Readability: The explicit type annotations make the code easier to understand, especially when working in teams or revisiting the code later.

These benefits make TypeScript a valuable tool for any developer, especially those working on larger projects. The Number Fact Finder project is a perfect way to experience these advantages firsthand.

Project Setup

Let’s set up our project. We’ll need Node.js and npm (Node Package Manager) installed on your system. If you don’t have them, you can download them from the official Node.js website. Once you have Node.js and npm installed, open your terminal or command prompt and follow these steps:

  1. Create a Project Directory: Create a new directory for your project. For example, you can name it number-fact-finder.
  2. Initialize npm: Navigate to your project directory in the terminal and run npm init -y. This command creates a package.json file, which manages your project’s dependencies and other settings.
  3. Install TypeScript: Install TypeScript as a development dependency by running npm install --save-dev typescript.
  4. Initialize TypeScript: Create a tsconfig.json file by running npx tsc --init. This file configures how TypeScript compiles your code.
  5. Create Source File: Create a new file named index.ts in your project directory. This is where we’ll write our TypeScript code.

Your project directory structure should now look something like this:

number-fact-finder/
├── node_modules/
├── index.ts
├── package.json
├── package-lock.json
└── tsconfig.json

Writing the TypeScript Code

Now, let’s write the code for our Number Fact Finder. We’ll break down the code into logical sections, explaining each part in detail.

1. Basic Structure and Input

First, we need to set up the basic HTML structure. We will create a simple HTML file to display the output.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Fact Finder</title>
</head>
<body>
    <h1>Number Fact Finder</h1>
    <input type="number" id="numberInput" placeholder="Enter a number">
    <button id="factButton">Get Fact</button>
    <div id="factResult"></div>
    <script src="index.js"></script>
</body>
</html>

Now, let’s create the index.ts file and start with the core logic. We’ll start by getting the input from the user. We will use the DOM (Document Object Model) to interact with the HTML elements.

// index.ts
const numberInput = document.getElementById('numberInput') as HTMLInputElement;
const factButton = document.getElementById('factButton') as HTMLButtonElement;
const factResult = document.getElementById('factResult') as HTMLDivElement;

In this code, we are:

  • Getting references to the HTML elements using their IDs.
  • Using type assertions (as HTMLInputElement, etc.) to tell TypeScript the type of the elements, which allows for better code completion and error checking.

2. Fetching Facts from an API

To get interesting facts about numbers, we’ll use a free API. There are several APIs available; for this tutorial, we will use the Numbers API, which provides facts about numbers. We’ll create a function to fetch the facts.

async function getNumberFact(number: number): Promise<string> {
  try {
    const response = await fetch(`http://numbersapi.com/${number}?json`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data.text;
  } catch (error) {
    console.error('Error fetching fact:', error);
    return 'Could not retrieve fact.';
  }
}

Here’s what the code does:

  • The getNumberFact function takes a number as input and returns a Promise that resolves to a string (the fact).
  • It uses the fetch API to make a GET request to the Numbers API. The API endpoint includes the number entered by the user.
  • It checks if the response is successful (status code 200-299). If not, it throws an error.
  • It parses the response as JSON.
  • It returns the fact from the JSON response.
  • It includes error handling to catch any issues during the API call.

3. Event Listener and Displaying the Fact

Now, let’s add an event listener to the button. When the button is clicked, we’ll get the number from the input field, fetch the fact, and display it.


factButton.addEventListener('click', async () => {
  const number = parseInt(numberInput.value, 10);

  if (isNaN(number)) {
    factResult.textContent = 'Please enter a valid number.';
    return;
  }

  const fact = await getNumberFact(number);
  factResult.textContent = fact;
});

In this part:

  • We add a click event listener to the factButton.
  • Inside the event listener, we get the value from the numberInput, parse it as an integer, and check if the input is a valid number.
  • If the input is valid, we call the getNumberFact function to fetch the fact.
  • We then update the factResult element with the fetched fact.

4. Compiling and Running the Application

To run the application, we need to compile the TypeScript code into JavaScript. Open your terminal and run the following command:

tsc index.ts

This command uses the TypeScript compiler (tsc) to compile the index.ts file into index.js. Then, open the HTML file (e.g., in a web browser). Enter a number in the input field, click the