Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to compile a Typescript file?
In this article we are going to explore TypeScript and how to compile and execute TypeScript files. TypeScript is an open-source programming language developed and maintained by Microsoft.
TypeScript is syntactically similar to JavaScript but adds additional features like static typing and object-oriented programming. Unlike JavaScript, TypeScript does not run directly in web browsers and must be compiled to JavaScript first.
TypeScript files need to be transpiled to JavaScript before they can be executed. This compilation process converts TypeScript syntax into standard JavaScript that browsers and Node.js can understand.
Prerequisites
Before compiling TypeScript files, you need to set up your development environment:
Download & Install Node.js and Node Package Manager (NPM)
Install the TypeScript compiler globally using NPM
Verify your installation with version checks
Installation Steps
Check if Node.js and NPM are installed:
// Check Node version node -v
// Check NPM version npm -v
Install TypeScript globally:
npm install -g typescript
Verify TypeScript installation:
tsc --version
Basic Compilation Example
Let's create a simple TypeScript file and compile it to JavaScript. Create a file named index.ts:
// index.ts let greet: string = "Welcome to"; let org: string = "TutorialsPoint!"; let tagLine: string = "SIMPLY LEARNING!"; console.log(greet + " " + org); console.log(tagLine);
Compilation Process
Compile the TypeScript file using the TypeScript compiler:
tsc index.ts
This command generates a JavaScript file named index.js in the same directory:
// Generated index.js var greet = "Welcome to"; var org = "TutorialsPoint!"; var tagLine = "SIMPLY LEARNING!"; console.log(greet + " " + org); console.log(tagLine);
Executing the Compiled Code
Run the generated JavaScript file using Node.js:
node index.js
Welcome to TutorialsPoint! SIMPLY LEARNING!
Compiler Options
TypeScript compiler provides various options for customizing the compilation process:
| Option | Description |
|---|---|
--target |
Specify ECMAScript target version |
--outDir |
Redirect output to specific directory |
--watch |
Watch for file changes and recompile |
Watch Mode Example
For development, use watch mode to automatically recompile when files change:
tsc index.ts --watch
Conclusion
Compiling TypeScript involves installing the TypeScript compiler via NPM and using the tsc command to transpile .ts files into JavaScript. The generated JavaScript can then be executed using Node.js or included in web applications.
