Installing TypeScript

Learn how to install and set up TypeScript in your development environment.

Prerequisites

Before installing TypeScript, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can download Node.js from the official Node.js website, which includes npm.

Step 1: Install TypeScript

You can install TypeScript globally on your machine using npm. Open your terminal or command prompt and run the following command:

npm install -g typescript

This command installs TypeScript globally, allowing you to use the tsc command anywhere on your machine.

Step 2: Verify the Installation

After installing TypeScript, you can verify the installation by checking the TypeScript version. Run the following command:

tsc --version

If TypeScript is installed correctly, you should see the version number displayed in your terminal.

Step 3: Initialize a TypeScript Project

To initialize a TypeScript project, create a new directory for your project and navigate into it. Then, run the following command to generate a tsconfig.json file:

tsc --init

The tsconfig.json file is used to configure the TypeScript compiler options for your project. You can customize it according to your project's requirements.

Step 4: Write Your First TypeScript File

Create a new TypeScript file with a .ts extension. For example, create a file named hello.ts and add the following code:

function greet(name: string) {
    return `Hello, ${name}!`;
}

let user = "World";
console.log(greet(user));

This simple TypeScript function takes a string parameter and returns a greeting message.

Step 5: Compile TypeScript to JavaScript

To compile your TypeScript code to JavaScript, run the TypeScript compiler using the following command:

tsc hello.ts

This command generates a hello.js file containing the compiled JavaScript code.

Step 6: Run the Compiled JavaScript

Finally, you can run the compiled JavaScript file using Node.js. Run the following command:

node hello.js

You should see the greeting message Hello, World! printed in the terminal.

Conclusion

You have successfully installed TypeScript and compiled your first TypeScript file. TypeScript provides many features that enhance the JavaScript development experience, including static typing, classes, and interfaces. You can now start exploring these features and integrating TypeScript into your projects.