Getting Started with TypeScript: Building Your First Interactive Web App

Learn how to create your first interactive web app using TypeScript with this beginner-friendly step-by-step tutorial.

TypeScript is a powerful programming language that builds on JavaScript by adding static types, making your code easier to understand and less prone to errors. In this tutorial, you'll learn the basics of TypeScript and create a simple interactive web app — a counter that increases and decreases with button clicks.

First, let's set up a basic HTML page where we will add our TypeScript-powered app.

typescript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>TypeScript Counter App</title>
</head>
<body>
  <h1>Simple Counter</h1>
  <button id="decrease">-</button>
  <span id="count">0</span>
  <button id="increase">+</button>
  <script src="app.js"></script>
</body>
</html>

Now, let's write our TypeScript code. Create a file named `app.ts`. This file will contain the logic for our counter. The main idea is to keep track of a count variable and update the displayed number when buttons are clicked.

typescript
let count: number = 0;

const countEl = document.getElementById('count') as HTMLSpanElement;
const increaseBtn = document.getElementById('increase') as HTMLButtonElement;
const decreaseBtn = document.getElementById('decrease') as HTMLButtonElement;

function updateDisplay() {
  countEl.textContent = count.toString();
}

increaseBtn.addEventListener('click', () => {
  count++;
  updateDisplay();
});

decreaseBtn.addEventListener('click', () => {
  count--;
  updateDisplay();
});

updateDisplay();

Next, compile the TypeScript code into JavaScript so the browser can run it. If you haven't installed TypeScript yet, you can do so via npm with `npm install -g typescript`. Then, run this command in your project directory:

typescript
tsc app.ts

This will generate an `app.js` file which is referenced in your HTML file. Open the HTML file in your browser, and you should see your interactive counter with working buttons.

To summarize, you've learned how to: - Set up a basic HTML page - Write TypeScript code that interacts with HTML elements - Use TypeScript's type annotations for better safety - Compile TypeScript to JavaScript for browser use TypeScript helps catch errors early and makes your code easier to maintain. From here, you can explore more advanced features like interfaces, classes, and modules to build bigger applications.