TypeScript with Node.js

In this chapter, we will explore how to use TypeScript with Node.js. TypeScript is a superset of JavaScript that adds static types, making it easier to catch errors during development. Node.js is a runtime that allows you to run JavaScript on the server. Combining these two technologies can lead to more robust and maintainable server-side applications.We will cover everything from setting up a TypeScript project with Node.js to advanced features like decorators and type guards. By the end of this chapter, you'll have a comprehensive understanding of how to develop Node.js applications using TypeScript.

Setting Up a TypeScript Project

Installing Node.js and npm/yarn

To start, ensure you have Node.js installed. You can download it from nodejs.org. npm (Node Package Manager) comes bundled with Node.js, but you can also use yarn, an alternative package manager. Install yarn with:

				
					npm install -g yarn

				
			

Initializing a Node.js Project

Create a new directory for your project and initialize a Node.js project:

				
					mkdir my-typescript-project
cd my-typescript-project
npm init -y

				
			

Adding TypeScript to Your Project

Install TypeScript and the necessary type definitions:

				
					npm install typescript ts-node @types/node --save-dev

				
			

Configuring TypeScript

Create a tsconfig.json file to configure TypeScript:

				
					{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

				
			

Project Structure

Set up your project structure:

				
					my-typescript-project/
├── src/
│   └── index.ts
├── tsconfig.json
├── package.json
└── node_modules/

				
			

Hello World Example

Create a simple index.ts file:

				
					const greeting: string = "Hello, TypeScript with Node.js!";
console.log(greeting);

				
			

Compile and run your TypeScript code using ts-node:

				
					npx ts-node src/index.ts

				
			

Working with Modules

Importing and Exporting Modules

TypeScript supports ES6 module syntax. Create a module math.ts:

				
					// src/math.ts
export const add = (a: number, b: number): number => a + b;
export const subtract = (a: number, b: number): number => a - b;

				
			

Use the module in index.ts:

				
					// src/index.ts
import { add, subtract } from './math';

const sum = add(5, 3);
const difference = subtract(5, 3);

console.log(`Sum: ${sum}`);
console.log(`Difference: ${difference}`);

				
			

Run the code:

				
					npx ts-node src/index.ts

				
			

Default Exports

You can also use default exports:

				
					// src/logger.ts
export default function log(message: string): void {
  console.log(message);
}

// src/index.ts
import log from './logger';

log("This is a default export example.");

				
			

Using Type Definitions

Installing Type Definitions

Many npm packages don’t include TypeScript type definitions. Use @types to install them:

				
					npm install @types/express --save-dev

				
			

Example with Express

Create a simple Express server:

				
					// src/server.ts
import express, { Request, Response } from 'express';

const app = express();
const port = 3000;

app.get('/', (req: Request, res: Response) => {
  res.send('Hello, TypeScript with Express!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

				
			

Update tsconfig.json to include the new entry point:

				
					{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

				
			

Compile and run the server:

				
					npx ts-node src/server.ts

				
			

Advanced TypeScript Features

Type Inference

TypeScript can infer types based on the assigned values:

				
					let message = "Hello, World!"; // inferred as string

				
			

Interfaces and Types

Define custom types and interfaces:

				
					interface User {
  id: number;
  name: string;
}

const user: User = {
  id: 1,
  name: "John Doe"
};

type Point = {
  x: number;
  y: number;
};

const point: Point = {
  x: 10,
  y: 20
};

				
			

Generics

Use generics to create reusable components:

				
					function identity<T>(arg: T): T {
  return arg;
}

console.log(identity<string>("Hello"));
console.log(identity<number>(123));

				
			

Decorators

Decorators are a special kind of declaration used on classes and methods:

				
					function logClass(target: any) {
  console.log(`Class decorated: ${target.name}`);
}

@logClass
class MyClass {
  constructor(public name: string) {}
}

const myClassInstance = new MyClass("Example");

				
			

Integrating with Build Tools

Using ts-node for Development

ts-node is a TypeScript execution engine for Node.js, useful for development:

				
					npx ts-node src/index.ts

				
			

Compiling TypeScript with tsc

Compile your TypeScript code to JavaScript for production:

				
					npx tsc

				
			

This command generates JavaScript files in the dist directory as specified in tsconfig.json.

Setting Up Nodemon for Automatic Restarts

Nodemon restarts your server automatically when it detects changes:

				
					npm install nodemon ts-node --save-dev

				
			

Add a script to package.json:

				
					"scripts": {
  "dev": "nodemon --exec ts-node src/index.ts"
}

				
			

Start the development server:

				
					npm run dev

				
			

Testing with TypeScript

Setting Up Jest

Install Jest and its TypeScript dependencies:

				
					npm install jest ts-jest @types/jest --save-dev

				
			

Create a Jest configuration file:

				
					// jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
};

				
			

Writing Tests

Create a simple test:

				
					// src/math.test.ts
import { add, subtract } from './math';

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});

test('subtracts 5 - 2 to equal 3', () => {
  expect(subtract(5, 2)).toBe(3);
});

				
			

Run the tests:

				
					npx jest

				
			

By combining TypeScript with Node.js, you can create scalable, maintainable server-side applications with enhanced type safety. We have covered the essentials from setting up a project to advanced features and testing. This comprehensive guide provides a strong foundation for building robust applications. Continue exploring TypeScript's extensive type system and Node.js's rich ecosystem to enhance your development skills further. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India