TypeScript Tutorial: Building a Simple Interactive Cryptocurrency Price Tracker

In the fast-paced world of finance, staying updated with cryptocurrency prices is crucial. Wouldn’t it be great to have a simple, interactive tool that displays real-time price data? This tutorial will guide you through building a cryptocurrency price tracker using TypeScript, providing a hands-on learning experience for beginners and intermediate developers. We’ll cover everything from setting up your development environment to fetching data from a public API and displaying it in a user-friendly interface. By the end of this tutorial, you’ll have a functional price tracker and a solid understanding of TypeScript fundamentals, API interaction, and front-end development principles.

Why Build a Cryptocurrency Price Tracker?

Cryptocurrencies have gained significant popularity, and with that comes the need for accessible and real-time price information. Building a price tracker offers several benefits:

  • Practical Application: You’ll learn how to fetch and display real-time data from an API, a skill applicable to various projects.
  • TypeScript Proficiency: You’ll solidify your understanding of TypeScript’s type system, object-oriented programming, and other core concepts.
  • Front-End Development: You’ll gain experience with HTML, CSS, and JavaScript (with TypeScript) to create an interactive user interface.
  • Personalization: You can customize the tracker to display your preferred cryptocurrencies and other relevant information.

Prerequisites

Before we begin, ensure you have the following:

  • Node.js and npm (or yarn) installed: This provides the runtime environment and package manager for your project.
  • A code editor: Visual Studio Code (VS Code) is highly recommended, but any editor will work.
  • Basic HTML, CSS, and JavaScript knowledge: Familiarity with these languages will be helpful.

Setting Up Your Development Environment

Let’s start by setting up our project. Open your terminal or command prompt and follow these steps:

  1. Create a Project Directory: Create a new directory for your project, for example, `cryptocurrency-tracker`.
  2. Initialize npm: Navigate to the project directory in your terminal and run `npm init -y`. This creates a `package.json` file.
  3. Install TypeScript: Install TypeScript and the TypeScript compiler globally by running `npm install -g typescript`.
  4. Create a `tsconfig.json` file: In your project directory, run `tsc –init`. This creates a `tsconfig.json` file, which configures the TypeScript compiler. You can customize this file to suit your project’s needs. We’ll use the default settings for this tutorial.
  5. Create Project Files: Create an `index.html` file for the user interface, an `index.ts` file for your TypeScript code, and a `style.css` file for styling.

Your project directory structure should look like this:

cryptocurrency-tracker/
  ├── index.html
  ├── index.ts
  ├── style.css
  ├── package.json
  └── tsconfig.json

Writing the HTML (index.html)

Let’s create the basic structure of our user interface in `index.html`:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cryptocurrency Price Tracker</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Cryptocurrency Price Tracker</h1>
  <div id="crypto-container">
    <!-- Cryptocurrency data will be displayed here -->
  </div>
  <script src="index.js"></script>
</body>
</html>

This HTML provides a basic structure with a title, a container to display the cryptocurrency data, and a link to your stylesheet and JavaScript file. The `<script src=”index.js”></script>` line is crucial; it links the compiled JavaScript file (generated from your TypeScript code) to your HTML.

Styling with CSS (style.css)

Now, let’s add some basic styling to `style.css` to make the tracker visually appealing:

body {
  font-family: sans-serif;
  margin: 0;
  padding: 20px;
  background-color: #f4f4f4;
}

h1 {
  text-align: center;
  color: #333;
}

#crypto-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.crypto-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin: 10px;
  padding: 15px;
  width: 300px;
  text-align: center;
}

.crypto-card h2 {
  margin-bottom: 10px;
  color: #007bff;
}

.crypto-card p {
  margin-bottom: 5px;
}

This CSS provides a basic layout and styling for the title, the cryptocurrency container, and individual cryptocurrency cards.

Writing the TypeScript Code (index.ts)

This is the core of our application. We’ll fetch cryptocurrency data from a public API, parse the data, and display it in the HTML. We’ll use the CoinGecko API for this tutorial. First, install the `axios` library to make HTTP requests:

npm install axios

Now, let’s write the TypeScript code in `index.ts`:

import axios from 'axios';

// Define an interface for the cryptocurrency data
interface CryptoData {
  name: string;
  symbol: string;
  current_price: number;
  price_change_percentage_24h: number;
}

// Function to fetch cryptocurrency data
async function getCryptoPrices(): Promise<CryptoData[]> {
  try {
    const response = await axios.get(
      'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false'
    );
    // Type assertion to ensure the response data matches our CryptoData interface
    return response.data as CryptoData[];
  } catch (error) {
    console.error('Error fetching data:', error);
    return [];
  }
}

// Function to create a cryptocurrency card
function createCryptoCard(crypto: CryptoData): HTMLDivElement {
  const card = document.createElement('div');
  card.classList.add('crypto-card');

  const priceChangeColor = crypto.price_change_percentage_24h > 0 ? 'green' : 'red';

  card.innerHTML = `
    <h2>${crypto.name} (${crypto.symbol.toUpperCase()})</h2>
    <p>Price: $${crypto.current_price.toFixed(2)}</p>
    <p style="color: ${priceChangeColor};">Change (24h): ${crypto.price_change_percentage_24h.toFixed(2)}%</p>
  `;
  return card;
}

// Function to display cryptocurrency data
async function displayCryptoData() {
  const cryptoData = await getCryptoPrices();
  const cryptoContainer = document.getElementById('crypto-container');

  if (cryptoContainer) {
    cryptoData.forEach(crypto => {
      const card = createCryptoCard(crypto);
      cryptoContainer.appendChild(card);
    });
  }
}

// Call the function to display data when the page loads
displayCryptoData();

Let’s break down this code:

  • Import axios: Imports the axios library for making API requests.
  • `CryptoData` Interface: Defines an interface to strongly type the data we expect from the API. This helps prevent errors and improves code readability.
  • `getCryptoPrices()` Function: This asynchronous function fetches data from the CoinGecko API. It uses `axios.get` to make the request and handles potential errors. It also includes a type assertion to ensure the API response matches the `CryptoData` interface.
  • `createCryptoCard()` Function: This function takes a `CryptoData` object and generates an HTML element (a `div` with a class of `crypto-card`) to display the cryptocurrency information. It also dynamically sets the color of the price change percentage based on whether it’s positive or negative.
  • `displayCryptoData()` Function: This function calls `getCryptoPrices()` to get the data, then iterates through the returned array, creating a card for each cryptocurrency and appending it to the `crypto-container` div in the HTML.
  • `displayCryptoData()` Call: Calls the `displayCryptoData()` function to initiate the process when the page loads.

Compiling and Running the Application

Now, let’s compile the TypeScript code and run the application:

  1. Compile TypeScript: In your terminal, run `tsc` in your project directory. This will generate an `index.js` file from your `index.ts` file.
  2. Open `index.html` in your browser: You can either double-click the `index.html` file or use a simple web server (like the one provided by VS Code’s Live Server extension) to view the application in your browser.

You should now see a list of cryptocurrency prices displayed in your browser.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to fix them:

  • Incorrect API Endpoint: Double-check the API endpoint URL for typos or incorrect parameters.
  • Data Type Mismatches: Ensure your data types in the `CryptoData` interface match the data returned by the API. Use type assertions if necessary.
  • CORS Errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, you may need to use a proxy server or configure your browser to allow cross-origin requests for development purposes.
  • Uncaught Errors: Use `try…catch` blocks to handle errors in your asynchronous functions, and log error messages to the console for debugging.
  • Incorrect DOM Manipulation: Make sure you correctly select the HTML elements using `document.getElementById()` and that you’re appending the generated elements to the correct parent element.

Enhancements and Customization

Here are some ways you can enhance and customize your cryptocurrency price tracker:

  • Add More Cryptocurrencies: Modify the API request to fetch data for more cryptocurrencies.
  • Implement Real-Time Updates: Use WebSockets or a similar technology to update the prices in real-time.
  • Add User Preferences: Allow users to select their preferred cryptocurrencies and display them in a custom order.
  • Add Charting: Integrate a charting library to visualize price trends over time.
  • Improve Styling: Enhance the CSS to create a more visually appealing and user-friendly interface.
  • Error Handling: Implement more robust error handling and display user-friendly error messages.

Key Takeaways

This tutorial has provided a comprehensive guide to building a cryptocurrency price tracker with TypeScript. We’ve covered the following key concepts:

  • Setting up a TypeScript project: Initializing the project, installing dependencies, and configuring the TypeScript compiler.
  • Working with APIs: Fetching data from a public API using `axios`.
  • Type Safety: Using interfaces to define data structures and ensure type safety.
  • DOM Manipulation: Dynamically creating and updating HTML elements using JavaScript.
  • Asynchronous Programming: Using `async/await` to handle asynchronous operations.

FAQ

  1. Q: Why is TypeScript better than JavaScript for this project?

    A: TypeScript provides static typing, which helps catch errors during development, improves code readability, and makes it easier to maintain and refactor your code. It also provides better autocompletion and code suggestions in your editor.

  2. Q: Where can I find other cryptocurrency APIs?

    A: There are many cryptocurrency APIs available, such as CoinMarketCap, Binance API, and CryptoCompare. Each API has its own documentation and usage requirements.

  3. Q: How can I deploy this application?

    A: You can deploy your application to a web hosting service like Netlify, Vercel, or GitHub Pages. These services allow you to easily deploy static websites.

  4. Q: What are the benefits of using a framework like React or Angular for this project?

    A: Frameworks like React and Angular provide features like component-based architecture, state management, and more advanced tools for building complex user interfaces. While this project is simple, a framework can be beneficial for larger, more complex applications.

You’ve now built a functional and informative cryptocurrency price tracker using TypeScript. This project not only equips you with practical skills in web development but also deepens your understanding of TypeScript’s capabilities. Remember that the best way to learn is by doing. So, experiment with the code, try different APIs, and add your own features to personalize the tracker. Keep exploring and building, and you’ll continue to grow as a developer. The knowledge gained from this project serves as a solid foundation for more complex web applications, and your ability to interact with APIs and manage data will be invaluable in future endeavors. The world of web development is constantly evolving, and your willingness to learn and adapt will be your greatest asset as you navigate through it.