To develop an Express.js application using TypeScript, you need to follow these steps:
- Install TypeScript: In the command-line tool or terminal, navigate to your project directory and run the following command:
npm install typescript --save-dev
```
This will install the latest version of TypeScript and all its dependencies.
2. Initialize TypeScript: In the command-line tool or terminal, navigate to your project directory and run the following command:
npx tsc –init
This will create a `tsconfig.json` file in your project directory, which contains configuration options for the TypeScript compiler.
3. Install Express and related TypeScript types: In the command-line tool or terminal, navigate to your project directory and run the following command:
`
npm install express @types/express –save
This will install Express and related TypeScript types.
4. Create a TypeScript file: In your project directory, create an `app.ts` file and add the following code:
`typescript
import express from ‘express’;
const app = express();
app.get(‘/’, (req, res) => {
res.send(‘Hello, Express!’);
});
app.listen(3000, () => {
console.log(‘Server started on port 3000’);
});
This will create a simple Express application that returns the message "Hello, Express!" at the root path.
5. Compile the TypeScript file: In the command-line tool or terminal, navigate to your project directory and run the following command:
`
npx tsc
This will compile your TypeScript file and generate a JavaScript file.
6. Run your application: In the command-line tool or terminal, navigate to the directory containing your JavaScript file and run the following command:
`
node app.js
npx tsc && node app.js
“`
This will start your application and output the message “Server started on port 3000” in the command-line tool or terminal.
In summary, to develop an Express.js application using TypeScript, you need to install TypeScript, initialize TypeScript, install Express and related TypeScript types, create a TypeScript file, compile the TypeScript file, and then run your application.