Installing Node.js, TypeScript, and Running Your First Program - Textnotes

Installing Node.js, TypeScript, and Running Your First Program


Learn how to set up a complete TypeScript development environment. This tutorial explains how to install Node.js, install TypeScript, use the TypeScript compiler, and run a TypeScript file step by step.

1. Installing Node.js

Node.js is required because the TypeScript compiler runs on Node.js. It also allows you to execute the compiled JavaScript code.

Steps to Install Node.js

  1. Visit the official Node.js website.
  2. Download the LTS (Long Term Support) version.
  3. Run the installer and follow the default installation steps.
  4. Restart the system after installation.

Verify Installation

Open Command Prompt or Terminal and run:


node -v
npm -v

If version numbers are displayed, Node.js and npm are installed successfully.

2. Installing TypeScript

TypeScript is installed using npm, which comes with Node.js.

Install TypeScript Globally

Run the following command:


npm install -g typescript

This installs the TypeScript compiler globally so it can be used from anywhere on the system.

Verify TypeScript Installation


tsc -v

The command should display the installed TypeScript version.

3. Using the TypeScript Compiler

The TypeScript compiler is called tsc. It converts TypeScript code into JavaScript.

Compile a TypeScript File

Create a file named app.ts:


let message: string = "Hello TypeScript";
console.log(message);

Compile the file:


tsc app.ts

This generates a JavaScript file:


app.js

Understanding Compilation

TypeScript checks:

  1. Type correctness
  2. Syntax errors
  3. Configuration rules from tsconfig.json

If errors are found, JavaScript output is not generated until they are fixed.

4. Running a TypeScript File

TypeScript files cannot be executed directly. They must first be compiled into JavaScript.

Run the Compiled JavaScript


node app.js

Output:


Hello TypeScript

Using tsconfig.json (Recommended for Real Projects)

Initialize a TypeScript project:


tsc --init

This creates a tsconfig.json file.

Example configuration:


{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true
}
}

Project structure:


project/
├── src/
│ └── app.ts
├── dist/
│ └── app.js
├── tsconfig.json

Compile the entire project:


tsc

Run the output:


node dist/app.js

Common Issues and Fixes

TypeScript command not found

Cause: Global npm path not set

Fix: Restart terminal or reinstall TypeScript

Node command not found

Cause: Node.js not installed or PATH not configured

Fix: Reinstall Node.js using LTS version

Conclusion

Setting up the TypeScript environment is straightforward and essential for modern development. Node.js provides the runtime, TypeScript provides type safety, and the TypeScript compiler bridges the gap between development and execution.