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.
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
Create a new directory for your project and initialize a Node.js project:
mkdir my-typescript-project
cd my-typescript-project
npm init -y
Install TypeScript and the necessary type definitions:
npm install typescript ts-node @types/node --save-dev
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"]
}
Set up your project structure:
my-typescript-project/
├── src/
│ └── index.ts
├── tsconfig.json
├── package.json
└── node_modules/
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
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
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.");
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
TypeScript can infer types based on the assigned values:
let message = "Hello, World!"; // inferred as string
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
};
Use generics to create reusable components:
function identity(arg: T): T {
return arg;
}
console.log(identity("Hello"));
console.log(identity(123));
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");
ts-node is a TypeScript execution engine for Node.js, useful for development:
npx ts-node src/index.ts
Compile your TypeScript code to JavaScript for production:
npx tsc
This command generates JavaScript files in the dist
directory as specified in tsconfig.json
.
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
Install Jest and its TypeScript dependencies:
npm install jest ts-jest @types/jest --save-dev
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
};
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 !❤️