Loading lesson path
TypeScript is a superset of JavaScript that adds optional static typing. It helps you catch errors early and write safer, more maintainable code.
TypeScript tutorial for more details. Using TypeScript with Node.js To use TypeScript in Node.js projects, you need to install TypeScript and a type definition manager:
Formula
npm install - g typescript npm install -- save - dev @types/nodeWrite your code in.ts files and compile them to JavaScript with: tsc yourfile.ts
Formula
1. Initialize a new Node.js project npm init - y
2. Install TypeScript and type definitions npm install -- save - dev typescript @types/nodeFormula
// Primitive types let isDone: boolean = false;let count: number = 10;
let name: string = 'TypeScript';
// Arrays let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob'];
// Tuples let user: [string, number] = ['Alice', 25];
// Enums enum Color {Red, Green, Blue}
let color: Color = Color.Green;// Interface interface User {
id: number;
name: string;
email?: string; // Optional property
}
// Type alias type Point = {
x: number;
y: number;
};
// Using the interface function printUser(user: User) {
console.log(`User: ${user.name}`);
}TypeScript with Node.js
// server.ts import http from 'http';
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, TypeScript!');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Formula
# Install required packages npm install express npm install -- save - dev @types/express// app.ts import express, { Request, Response } from 'express';
interface User {
id: number;
name: string;
}
const app = express();
app.use(express.json());Formula
// In - memory database let users: User[] = [];// Get all users app.get('/users', (req: Request, res: Response) => {
res.json(users);
});
// Add new user app.post('/users', (req: Request, res: Response) => {
const user: User = req.body;
users.push(user);
res.status(201).json(user);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});TypeScript Configuration tsconfig.json
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}target : Specify ECMAScript target version module : Specify module code generation strict : Enable all strict type checking options outDir : Redirect output structure to the directory rootDir : Specify the root directory of input files Why Use TypeScript with Node.js?
: Catch errors at compile time rather than runtime
: Superior autocompletion and code navigation
: Types serve as documentation
: Safely rename variables and update code
: Add types incrementally to existing JavaScript code