DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Bootstrapping a TypeScript Node.js Application

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • npm init -y creates a package.json.
  • npx tsc --init generates a tsconfig.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);
Enter fullscreen mode Exit fullscreen mode

Notice that we explicitly declare x as a number.


Step 4 – Compile TypeScript to JavaScript

Run the compiler to generate plain JavaScript:

tsc -b
Enter fullscreen mode Exit fullscreen mode

This produces a a.js file (depending on your tsconfig.json). If you open it, you’ll see:

const x = 1;
console.log(x);
Enter fullscreen mode Exit fullscreen mode

➡️ 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);
Enter fullscreen mode Exit fullscreen mode

Compile again:

tsc -b
Enter fullscreen mode Exit fullscreen mode

This time, you’ll see errors in the console:

Type '"harkirat"' is not assignable to type 'number'.
Enter fullscreen mode Exit fullscreen mode

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)