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
- Visit the official Node.js website.
- Download the LTS (Long Term Support) version.
- Run the installer and follow the default installation steps.
- Restart the system after installation.
Verify Installation
Open Command Prompt or Terminal and run:
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:
This installs the TypeScript compiler globally so it can be used from anywhere on the system.
Verify TypeScript Installation
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:
Compile the file:
This generates a JavaScript file:
Understanding Compilation
TypeScript checks:
- Type correctness
- Syntax errors
- 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
Output:
Using tsconfig.json (Recommended for Real Projects)
Initialize a TypeScript project:
This creates a tsconfig.json file.
Example configuration:
Project structure:
Compile the entire project:
Run the output:
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.