Skip to content

TypeScript Installation

To start using TypeScript, you need to install the TypeScript compiler (tsc). The compiler is responsible for converting TypeScript code (.ts files) into JavaScript code (.js files) that browsers or Node.js can run.

The most common way to install TypeScript is through npm (Node.js package manager). Therefore, before installing TypeScript, make sure Node.js and npm are already installed on your system.

1. Check Node.js and npm

Open your terminal or command line tool and enter the following commands to check if Node.js and npm are installed:

bash
node -v
npm -v

If the commands return version numbers (e.g., v18.17.0), they are successfully installed. If the command is not found, you need to visit the Node.js official website to download and install it. npm will be installed along with Node.js.

2. Install TypeScript Globally

We typically install the TypeScript compiler globally, so you can use the tsc command anywhere in any project.

Run the following command in your terminal:

bash
npm install -g typescript
  • npm install is the installation command.
  • The -g flag means "global," meaning this package will be installed in the system's global directory, not in the current project.
  • typescript is the name of the package we want to install.

After installation is complete, you can verify that TypeScript is successfully installed and check its version with the following command:

bash
tsc -v

If successful, it will output the TypeScript compiler version number, such as Version 5.2.2.

3. Write Your First TypeScript File

Now that you have TypeScript installed, you can write your first TypeScript file.

  1. Create a new folder, for example ts-project.
  2. Create a file named hello.ts in the folder.
  3. Enter the following code in the hello.ts file:
typescript
function greet(name: string) {
    console.log("Hello, " + name + "!");
}

greet("World");

Note that we specified the type of the greet function's parameter name as string.

4. Compile TypeScript File

Now, we need to compile the hello.ts file into JavaScript. In the terminal, make sure you are inside the ts-project folder, then run the following command:

bash
tsc hello.ts

After execution, you will find a new hello.js file in the folder. Looking at its content, you'll see that TypeScript's type annotations have been removed:

javascript
function greet(name) {
    console.log("Hello, " + name + "!");
}
greet("World");

5. Run JavaScript File

This generated hello.js file is a standard JavaScript file, which you can run using Node.js:

bash
node hello.js

The terminal will output:

Hello, World!

Congratulations! You have successfully installed TypeScript and completed the compilation and execution of your first program.

Content is for learning and research only.