Getting Started with TypeScript: Setting Up Your First Project

Learn how to set up your first TypeScript project with easy-to-follow steps for beginners.

TypeScript is a popular programming language that builds on JavaScript by adding static types, making your code easier to understand and less error-prone. If you're new to TypeScript and want to set up your first project, this tutorial will guide you step-by-step.

First, you need to have Node.js installed on your computer because TypeScript runs on Node and uses npm (Node Package Manager) to manage packages. You can download Node.js from its official website.

Once Node.js is installed, open your terminal or command prompt and follow these steps:

1. Create a new folder for your project and navigate into it:

typescript
mkdir my-typescript-project
cd my-typescript-project

2. Initialize a new Node.js project (this will create a package.json file):

typescript
npm init -y

3. Install TypeScript as a development dependency:

typescript
npm install typescript --save-dev

4. Initialize a TypeScript configuration file (tsconfig.json). This file helps you configure TypeScript compiler options:

typescript
npx tsc --init

The created tsconfig.json file contains default settings. You can leave them as is for now.

5. Now, create your first TypeScript file. Let's create a simple program that prints a message to the console.

typescript
touch index.ts

6. Open index.ts and add the following code:

typescript
const greet = (name: string): string => {
  return `Hello, ${name}! Welcome to TypeScript.`;
};

console.log(greet('World'));

7. To compile your TypeScript code into JavaScript, run:

typescript
npx tsc

This will generate an index.js file with the compiled JavaScript.

8. Finally, run the JavaScript file using Node.js:

typescript
node index.js

You should see the message: Hello, World! Welcome to TypeScript.

Congratulations! You've set up your first TypeScript project and written a simple program. As you continue learning, you can explore other TypeScript features such as interfaces, enums, and advanced type annotations.