TypeScript has become the go-to choice for many developers who want type safety and cleaner code on top of JavaScript. In this article, we’ll walk step by step through setting up a simple TypeScript + Node.js application to see how TypeScript catches errors before your code even runs.
Step 1 – Install the TypeScript Compiler
First, install TypeScript globally on your system so you can use the compiler (tsc
) in any project:
npm install -g typescript
Step 2 – Initialize a New Node.js Project
Let’s set up a fresh project folder with TypeScript support:
mkdir node-app
cd node-app
npm init -y
npx tsc --init
-
npm init -y
creates apackage.json
. -
npx tsc --init
generates atsconfig.json
, which holds your TypeScript configuration.
At this point, your project has the essentials to start writing .ts
files.
Step 3 – Create Your First TypeScript File
Inside your project, create a file called a.ts
:
const x: number = 1;
console.log(x);
Notice that we explicitly declare x
as a number
.
Step 4 – Compile TypeScript to JavaScript
Run the compiler to generate plain JavaScript:
tsc -b
This produces a a.js
file (depending on your tsconfig.json
). If you open it, you’ll see:
const x = 1;
console.log(x);
➡️ No TypeScript annotations remain. The code is now just regular JavaScript, ready to run in Node.js.
Step 5 – Experience Type Safety
Now let’s test TypeScript’s power. Change the file:
let x: number = 1;
x = "harkirat"; // ❌ assigning a string to a number
console.log(x);
Compile again:
tsc -b
This time, you’ll see errors in the console:
Type '"harkirat"' is not assignable to type 'number'.
And importantly: no new .js
file is generated.
That’s TypeScript preventing invalid code from making it into your runtime.
Why This Matters
This small example highlights the key advantage of TypeScript:
- You catch type errors at compile time, before they can break your application at runtime.
- TypeScript enforces contracts in your code, making large projects more predictable and easier to maintain.
With just a few commands, we bootstrapped a TypeScript Node.js app and saw how it safeguards us against common mistakes.
✨ Next steps: explore interfaces, classes, generics, and integrate TypeScript with frameworks like Express to build type-safe backends.
Top comments (0)