📜  typescript final example - TypeScript (1)

📅  最后修改于: 2023-12-03 15:20:42.948000             🧑  作者: Mango

Typescript Final Example - TypeScript

TypeScript is a popular programming language that adds static typing and other features to JavaScript. It is often used to develop large-scale web applications and is a great choice for developers who want the benefits of strong typing without sacrificing the dynamic and flexible nature of JavaScript.

In this final example, we'll take a look at how TypeScript can be used to develop a simple web application. We will be using the Node.js runtime environment and the Express web framework to create a basic server that serves up a single web page.

Step 1 - Setup

To get started, we will need to install some dependencies. You can do this by running the following command in your terminal:

npm install typescript express @types/express

This will install TypeScript, Express, and the required type definitions for TypeScript.

Step 2 - Create the Server

Next, we will create the server that will serve up our web page. We will do this by creating a new TypeScript file called server.ts. Here's what the contents of this file should look like:

import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

In this code, we import the Express module and create a new instance of the express() class. We then define a single route that will respond to HTTP GET requests to the root path ("/") by sending the text "Hello World!" back to the client. Finally, we start the server listening on port 3000 and log a message to the console to indicate that the server is running.

Step 3 - Compile and Run the Code

Now that we have our server code written, we need to compile it into JavaScript so that Node.js can execute it. To do this, we will run the following command in our terminal:

tsc server.ts

This will compile our TypeScript code into a JavaScript file called server.js.

To run the application, we simply need to run the following command:

node server.js

This will start the server running on port 3000. If you open a web browser and navigate to http://localhost:3000/, you should see the message "Hello World!" displayed on the page.

Conclusion

In this final example, we've seen how TypeScript can be used to develop a simple web application using the Express web framework. We've learned how to set up a basic server, define routes, and compile and run the code using Node.js. With this knowledge, you should now be able to start building your own TypeScript web applications and taking advantage of its strong typing and other features.