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:
mkdir my-typescript-project
cd my-typescript-project2. Initialize a new Node.js project (this will create a package.json file):
npm init -y3. Install TypeScript as a development dependency:
npm install typescript --save-dev4. Initialize a TypeScript configuration file (tsconfig.json). This file helps you configure TypeScript compiler options:
npx tsc --initThe 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.
touch index.ts6. Open index.ts and add the following code:
const greet = (name: string): string => {
return `Hello, ${name}! Welcome to TypeScript.`;
};
console.log(greet('World'));7. To compile your TypeScript code into JavaScript, run:
npx tscThis will generate an index.js file with the compiled JavaScript.
8. Finally, run the JavaScript file using Node.js:
node index.jsYou 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.