This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

What is the TypeScript

TypeScript is a superset of JavaScript that extends JavaScript syntax and supports the ECMAScript 6 standard.

What’s good about TypeScript

Advantage 1: TS static typing can avoid some coding problems

/ / ordinary JavaScript
// Define a function
function jsTotal(data) {
    return data.x + data.y
}
// Call the function
jsTotal()  // If no parameter is passed, no error will be reported in the editor
Copy the code

Error: Cannot read property ‘x’ of undefined error: Cannot read property ‘x’ of undefined error: Cannot read property ‘x’ of undefined

// TypeScript
// Define a function as well
function tsTotal(data: { x: number, y: number }) {
    return data.x + data.y
}

tsTotal()   // The editor will be marked red with an error message
Copy the code

TypeScript can detect errors when writing code that calls functions without passing arguments, and the editor promotes errors: Expected 1 arguments, but got 0.

Beyond the advantages of this example, of course, there are: Advantage two: the code hints are friendlier. Advantage 3: TS code is easier to read, while JS needs to dig into the code logic to know the meaning of parameters. Four advantages:…

TypeScript environment lapping

1. Install Node

It is recommended to install long-term stable versions of Node, which are easy to install and should be installed frequently as front-end developers, so I won’t go into details here.

Install TypeScript

Run the NPM install typescript -g command

TypeScript run

TypeScript code cannot run directly in a browser, so we need to compile TypeScript files first, converting TS files to JS files. Run TSC xxx.ts

XXX represents the file name, and a js file with the same name will be added after compilation. Normally, we run the compiled js file with Node: Node xxx.js

You might think it’s a hassle to do two things every time you run your code. So here’s a simple way to do it. The ts-Node tool must be installed globally. Run the NPM install ts-node -g command

You can now run TypeScript code directly from the ts-node xxx.ts command.

At this point the TypeScript environment is lapped up and ready to start coding.