Share
Explore

Get your Controller running in TypeScript

References:

Install Node.js runtime environment to run JavaScript on your server, outside a browser. It's necessary for using packages like Express.js and for running your server-side JavaScript or TypeScript code.

Here are the steps to install Node.js:
Windows/Mac:
Go to the official Node.js website's .
Download the installer appropriate for your system. You'll see options for Windows and macOS.
Once the installer is downloaded, run it and follow the prompts in the installation process.
Linux:
You can use a package manager to install Node.js. For Ubuntu, the package manager is apt. Here's how you can install Node.js:
bashCopy codesudo apt updatesudo apt install nodejs
You will also want to install npm (Node Package Manager), which is used to install Node.js packages. It's usually installed with Node.js, but if it's not, you can install it with:
bashCopy codesudo apt install npm
Verify Installation:
To ensure that Node.js and npm are installed, you can check their versions. Open a new terminal/command prompt window and type:
bashCopy codenode --versionnpm --version

To switch from JavaScript to TypeScript, we need to make some modifications to our code and setup:

Step 1: Install TypeScript

You can install TypeScript globally by using:
bashCopy codenpm install -g typescript
Or you can install it as a development dependency in your project:
bashCopy codenpm install --save-dev typescript
Step 2: Install Typings
You'll also need typings for Node.js and Express.js to provide type checking and IntelliSense:
bashCopy codenpm install --save-dev @types/node @types/express
Step 3: Create a tsconfig.json
You'll need a tsconfig.json in your project root to set up your TypeScript configuration. Here's a basic one:
jsonCopy code{ "compilerOptions": { "target": "ES2018", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true, }, "include": ["./src/**/*.ts"], "exclude": ["node_modules"]}
This configuration will output the transpiled JavaScript files into a directory named dist and will process TypeScript files located in the src directory.
Step 4: Convert server1.js to server1.ts
Now, let's rewrite the server1.js file into TypeScript. Note that the modifications in the code are mostly type annotations and the logic remains unchanged:
typescriptCopy code// server1.ts
import express, { Request, Response } from 'express';const app = express();app.use(express.json());
interface Book { id: string; title: string; author: string; // Add more fields if necessary}
let books: Book[] = [];
app.get('/', (req: Request, res: Response) => { res.send('Hello World!');});
app.get('/books', (req: Request, res: Response) => { res.json(books);});
app.post('/books', (req: Request, res: Response) => { const book: Book = req.body; books.push(book); res.status(201).send();});
app.put('/books/:id', (req: Request, res: Response) => { const id = req.params.id; const book: Book = req.body;
const index = books.findIndex((book) => book.id === id); if (index !== -1) { books[index] = book; res.send(); } else { res.status(404).send(); }});
app.delete('/books/:id', (req: Request, res: Response) => { const id = req.params.id;
const index = books.findIndex((book) => book.id === id); if (index !== -1) { books.splice(index, 1); res.send(); } else { res.status(404).send(); }});
app.listen(3001, () => console.log('Server running on port 3001'));
Step 5: Transpile TypeScript
In your project root directory, run:
bashCopy codetsc
This command transpiles your TypeScript files into JavaScript files, as specified in your tsconfig.json.
Step 6: Run Your Server
Since our tsconfig.json outputs the JavaScript files into dist directory, you can start the server with:
bashCopy codenode dist/server1.js
Optional: Setting Up Nodemon and ts-node for Development
For development, you might want your server to restart automatically every time you make changes. We can use nodemon and ts-node for this. ts-node is a TypeScript execution environment for Node.js, and nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your Node application.
You can install these as dev dependencies:
bashCopy codenpm install --save-dev nodemon ts-node
Then, add a script to your package.json:
jsonCopy code"scripts": { "dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/server1.ts"}
Now you can run your TypeScript server with:
bashCopy codenpm run dev
And it will automatically restart whenever you save changes to a TypeScript file.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.