Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Writing in the front

TypeScript is a superset of JavaScript that compiles into pure JavaScript code.

The main reason for TypeScript is that JavaScript can be used to develop complex projects, but it lacks reliability and requires us to add a lot of business logic to determine the robustness of the code.

TypeScript can run in a browser environment, node. js, or ECMAScript3 or higher JavaScript engines.

The problem of JavaScript

The main problems with JavaScript are as follows:

  1. JavaScript type exceptions are only detected at runtime.
  2. Because the type of JavaScript function is not clear, it may cause the final function of the function to cause problems, as shown in this code:
function sum(x, y){
  return x + y
}
sum(100.'100') / / 100100
Copy the code

The advantage of the TypeScript

JavaScript is a dynamically typed programming language. Dynamically typed means you don’t know whether the data type is Number or String at compile time. TypeScript, on the other hand, is a statically typed programming language. Statically typed means you write a variable knowing what its data type is

let num: number = 6;
Copy the code

The num variable must be of type number from beginning to end, and an exception will be thrown if a string is assigned to it.

So here are TypeScript’s advantages:

  1. During development, errors can be located so that we can check for errors
  2. Reduces unnecessary type checking in our development process
  3. Statically typed code prompts are superior to statically typed code prompts.
  4. This is easier when refactoring your project
  5. Statically typed code is more semantically oriented and readable than dynamically typed code.

TypeScript runtime environment

TypeScript runs on top of node.js, so install Node.js first.

Install Node.js and other operations to ignore

The command to install TypeScript is as follows

npm install -g typescript@3.6.4
Copy the code

I can specify the version number by @ or not

After installing TypeScript, you also need to install a TS-Node tool. If you install the tool, you cannot run TS code directly. You need to write THE TS code in JavaScript to execute it. The execution process is as follows

# Compile TS code
tsc demo.ts 
Js file, and it's ready to run
Copy the code

Once the Node-TS tool is installed, you can execute the TS code directly. The steps are as follows

# 1. Global installation
npm install -g ts-node@8.4.1
# 2. Run the code
ts-node demo.ts
Copy the code

Note that the installation directory must be in the environment variable, otherwise an error will be reported.