The tsc Compiler
Let's set up a simple TypeScript Node.js application on your local machine. Follow these steps to get started:
Step 1 - Install tsc
/TypeScript Globally
First, install TypeScript globally using npm.
npm install -g typescript
Step 2 - Initialize a Node.js Project with TypeScript
Create a new directory for your Node.js application and initialize it with TypeScript.
mkdir node-app
cd node-app
npm init -y
npx tsc --init
These commands will create your project directory and initialize it with package.json
and tsconfig.json
.
Step 3 - Create a a.ts
File
Create a new TypeScript file named a.ts
and add the following code:
const x: number = 1;
console.log(x);
Step 4 - Compile the .ts
File to a .js
File
Use the TypeScript compiler to compile your TypeScript file into JavaScript.
tsc -b
Step 5 - Check the Generated a.js
File
Open the generated a.js
file. You'll see that it contains plain JavaScript code with no type annotations.
var x = 1;
console.log(x);
Step 6 - Modify a.ts
to Assign x
to a String
Change a.ts
by converting const
to let
and assigning x
to a string:
let x: number = 1;
x = "something other than number"; // This will cause a type error
console.log(x);
Step 7 - Recompile the Code
Compile the code again with the TypeScript compiler:
tsc -b
You will see errors in the console indicating type mismatches. Additionally, notice that no a.js
file is generated this time due to the type errors.
Last updated
Was this helpful?