I. Environment configuration

The paternity of TypeScript (TS for short in this series) is not a topic for discussion. If you are interested, go to Baidu. TS is a superset of javascript, which means it has more extensions to javascript, it has everything that javascript has, and it has everything that javascript doesn’t have.

The only problem with it, however, is that it can’t run naked in the browser. It has to dress up to get out of the house.

1. Install node

Official website download:

https://nodejs.org/en/
Copy the code

My environment is Win10 64-bit, so I downloaded this 14.17.0LTS version. The installation process is all the way to the end.

2. Install TS

npm install -g typescript
tsc -v // Check the version number
Copy the code

The TSC -v command can be used to check the version number of ts installed in your directory and, otherwise, indirectly verify that you have successfully installed the TS runtime environment.

2. Editor selection

Vscode is preferred. The first is light weight, and the second is the same as TS is wechat’s own things, are born of the same mother, must be very tacit understanding, the two together absolutely do not delay.

Of course, you can choose webstorm,sublime text, notepad++,atom, etc. As a modern coder, the possibilities for your happiness are endless. There are so many options.

Third, the first TS program

Create the demo.ts file as follows:

let str = "Hello world"
console.log(str)
Copy the code

As mentioned earlier, the browser cannot run TS programs directly. The first step is to compile the demo. TS file into js code:

tsc demo.ts
Copy the code

After executing, the folder will have a demo.js file:

At this point you can play with the demo.js file just as you would with javascript. Instead of running it in an HTML file, I’ll run it directly from a command line window via Node:

As we hoped, the application in Demo. Ts ran successfully.

4. Configure automatic compilation of TS code for vscode

Because there are programmers in this world, there will be all kinds of incredible invention and creation (actually lazy), for our life to bring a lot of cheap. The same is true for TS programs. We don’t want to have to manually execute TSC XXX.ts every time we write TS code. Now let’s configure automatic compilation of TS programs.

(1) Generate the configuration file

Execute the following code in the project root directory:

PS F:\study\typescript\demo01> tsc --init
message TS6071: Successfully created a tsconfig.json file.
Copy the code

Back in the directory, there is a tsconfig.json file. Its contents:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true, /* Enable incremental compilation */
    "target": "es5"./* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs"./* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [], /* Specify library files to be included in the compilation. */
    // "allowJs": true, /* Allow javascript files to be compiled. */
    // "checkJs": true, /* Report errors in .js files. */
    // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true, /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true, /* Generates corresponding '.map' file. */
    // "outFile": "./", /* Concatenate and emit output to single file. */
    // "outDir": "./", /* Redirect output structure to the directory. */
    // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true, /* Enable project compilation */
    // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
    // "removeComments": true, /* Do not emit comments to output. */
    // "noEmit": true, /* Do not emit outputs. */
    // "importHelpers": true, /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true./* Enable all strict type-checking options. */
    // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true, /* Enable strict null checks. */
    // "strictFunctionTypes": true, /* Enable strict checking of function types. */
    // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true, /* Report errors on unused locals. */
    // "noUnusedParameters": true, /* Report errors on unused parameters. */
    // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
    // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */

    /* Module Resolution Options */
    // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
    // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [], /* List of folders to include type definitions from. */
    // "types": [], /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true./* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true./* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */}}Copy the code

(2) Modify the configuration

In the tsconfig.json file, find the following two items and modify them. If they are commented out, open comments:

//"outDir": "./js",  
"strict": true.Copy the code

“OutDir “: “./js”, is the compiled js directory, “strict”: false, and change true to false,

(3) select VScode automatic compilation

1, configuration,

Menu bar: Terminal —-> Run tasks —-> In the configuration menu that opens, click on typescript to expand the current directory and select the tsconfig.json file. At this point, a.vscode folder with a tasks.json file will be generated. Let’s open it up:

{
	"version": "2.0.0"."tasks": [{"type": "typescript"."tsconfig": "demo01/tsconfig.json"."problemMatcher": [
				"$tsc"]."group": "build"."label": "TSC: build - demo01/tsconfig.json"}}]Copy the code

This file is used by vscode to listen for ts file changes and implement automatic synchronous compilation.

2. Start the task

Menu bar: terminal —-> Run the task enter TSC press Enter

When you see this, as shown, VScode has started automatic compilation. Now let’s try some code.

PS: unable to redeclare block scope variable “XXX” problem.

It’s no surprise that when you’ve done the above, and you’re feeling good, you find yourself writing down a bunch of habitual variables with the same name, such as STR,arr,fn, etc., you can’t write anymore. Vscode tells you that you cannot redeclare block-scoped variables

To fix this, just add the following at the end of your code:

export {};

Here’s the full content of my Demo1.ts:

function foo(args:string){
    return console.log(args);
}
let str:string = "Holle World ~";
foo(str);
export {};
Copy the code

Analysis of the reasons for this problem: 1. It indicates that the variables of TS cannot be defined repeatedly (within the same scope). 2.