The tsc Compiler
The tsc
(TypeScript Compiler) is the official tool provided by TypeScript to compile .ts
files into .js
. Let’s go through the process of bootstrapping a simple TypeScript Node.js application and explore the features of the tsc
compiler.
Step 1 - Install tsc
/TypeScript Globally
To install the TypeScript compiler globally on your system, run the following command:
npm install -g typescript
Step 2 - Initialize an Empty Node.js Project with TypeScript
Set up a new Node.js project and initialize TypeScript:
mkdir node-app
cd node-app
npm init -y
npx tsc --init
These commands will:
- Create a new directory
node-app
- Initialize a
package.json
file for your Node.js project - Generate a
tsconfig.json
file, which contains the TypeScript configuration options
Step 3 - Create a a.ts
File
Add a simple TypeScript file to your project:
const x: number = 1;
console.log(x);
Save this as a.ts
.
Step 4 - Compile the .ts
File to a .js
File
Use the tsc
command to compile your TypeScript code:
tsc -b
This will generate a corresponding JavaScript file a.js
.
Step 5 - Explore the Generated JavaScript File
Open the newly created a.js
file to observe the output. You’ll notice that:
- The TypeScript code is compiled into plain JavaScript.
- There are no TypeScript-specific constructs in the
.js
file.
Step 6 - Modify the Code to Introduce a Type Error
Update your a.ts
file:
let x: number = 1;
x = "harkirat"; // Error: Type 'string' is not assignable to type 'number'
console.log(x);
Here, the const
is changed to let
, and x
is assigned a string value.
Step 7 - Compile the Code Again
Run the TypeScript compiler:
tsc -b
Observe the errors in the console. Since TypeScript enforces type safety, the compilation will fail, and no updated a.js
file will be generated.
Key Benefits of Using tsc
- Type Safety: Catch type errors during compile time.
- Code Integrity: Ensures a robust codebase by preventing invalid type assignments.
- Efficient Development: Reduces runtime errors by detecting issues early in the development process.
This demonstrates how the tsc
compiler is a powerful tool for maintaining type safety and enhancing code reliability in TypeScript projects.