📜  typescript hello world - TypeScript (1)

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

TypeScript Hello World

TypeScript is a statically-typed superset of JavaScript that adds optional static typing, classes, and interfaces. It compiles to clean, readable JavaScript, which makes it a great choice for large-scale applications.

Setup

Before we can start coding in TypeScript, we need to set up a development environment. You will need to have Node.js installed on your machine.

  1. Open up your terminal and navigate to the folder where you want to create your project.
  2. Run the following command to initialize a new Node.js project:
npm init -y
  1. Next, install TypeScript as a development dependency:
npm install --save-dev typescript
  1. Create a new file called index.ts. This is where we will write our TypeScript code.
Writing TypeScript Code

Let's start by creating a simple "Hello, World!" program in TypeScript. Open up index.ts and add the following code:

const greeting: string = "Hello, World!";
console.log(greeting);

In this example, we have created a constant called greeting that is of type string. We have assigned the value "Hello, World!" to this constant. Finally, we have printed the value of greeting to the console using the console.log function.

Running the Code

Now that we have written our TypeScript code, we need to compile it to JavaScript. In your terminal, run the following command:

npx tsc index.ts

This will compile your TypeScript code to JavaScript and create a new file called index.js.

Finally, run the following command to execute your code:

node index.js

You should see the following output in your terminal:

Hello, World!

Congratulations! You have written and executed your first TypeScript program.

Conclusion

TypeScript is a powerful tool that can help you write cleaner, more structured code. It takes a bit of effort to set up, but the additional benefits are well worth it. Get started with TypeScript today and see how it can improve your development experience.