1. Why learn TypeScript?

JavaScript has a lot of freedom to write, most notably the concept that javaScript has no types. The notes were made in combination with the official documents of li Lichao, a professor of Silicon Valley.

For example:

// the variable declared by JS is dynamically typed

let a = 0 // A numeric type
	a='hello'// A becomes a string again
	a=true// a becomes a BooleanThis looks easy to write, but not easy to maintain during project development because variable types can be easily modified. Accidentally changing the type when the variable is needed in multiple places. Even if an error occurs, it will not report an error in the modified place, but in the call to report an error, so the investigation consumes time.Copy the code

TypeScript addresses this problem by extending JavaScript and adding a superset of JS with type TS. It is a language built on top of JS and can be executed on any platform that supports JS. But TS cannot be executed directly by the JS parser (that is, the browser).

2. The TypeScript installation

Note that node.js has been installed on your computer

1. Enter the cli

npm i -g typescript // Global installation
Copy the code

2. Create an. Ts file

The demo. Ts fileletVariable: type = value;let  a : Number=30;
Copy the code

3. Run the TSC xxx.ts command to compile the TS file into a JS file

3.TypeScript type declarations

Type declarations are one of the most important features of TS. When a variable has a specified type, an error is reported if the variable is assigned a value other than the specified type.

Variables:let a : Number;
		a = 10;
    
	// Can also be written as:
    
    let a : Number = 10 / / common
	
	TS can automatically type check variables if they are declared and assigned at the same time
	// So the above can be abbreviated as
    
    let a = 10(not recommended)// In JS functions do not take into account the type and number of arguments
	// TS can specify the number of arguments and the type of the return value
	
	function sum ( a : Number. b : Number) :Number{//(this is the return type)
      	
        return a + b
    }
Copy the code

TypeScript type

type describe
String String type
Nubmer Numeric types
Boolean Boolean value type
Object Object type
Array An array type
any Any type (not recommended)
unknown Type safe any type
void A null value (undefined)
never It can’t be any value
tuple Tuple, TS new type, fixed length array
enum Enumeration, TS new type

1. Simple types

/ / 1. The string
let name : String 
	name = "I can write the following format."
/ / 2. The numerical values
let age : Number = 18;

/ / 3. The Boolean type
let isUser :Boolean = false;
 
Copy the code

2. Any Any type

Any Any type is not recommended.

3. The unknown type

// Unknown is the any type of type safety
letUser: unknown;letName: unknown. user="The Eight Turtles.";// Note: Variables of unknown type cannot be directly assigned to other variablesSuch as:letName = user is an error and we can use type assertion// Type assertion, which can be used to tell the parser the actual type of a variable
   name = user as String
   / / or
   name = <string> user
  
Copy the code

4. The void type

The void type generally represents a null value.

Common scenario: When a method does not return a value

function sum (num1:Number,num2:Number) :void{
	console.log(num1)
}
Copy the code

5. Never type

The never type indicates that the result is never returned.

Usage scenario: Throws an exception

function  fn() :never{
	
	throw new Error ("Error reported")//JS fails to proceed after an error occurs
}
Copy the code

6. The object type


	// Often used to specify which attributes are contained in an object
	// Syntax: {attribute name: type}
	// Add? To the attribute name. Indicates that the property is optional
 let a :{ name : string, the age? :Number}
 
 		
	 // Note that the name attribute fails if no value is assigned
 a={name:"The Tortoise"} or a = {name:"The Eight Turtles.".age:19} 



	//[XXX :string]:any Indicates the name of an attribute in the form of a string
let c :{name : string ,[rname : string ] : any} c= {name:"The Eight Turtles.", the age:18Gender:"Male", hello:"Hello"} Set the type declaration syntax for the function structure: (parameters: type, parameters: type...) => Return value typelet d  (a:number.b:number) = >number
		   d = function (n1:number,n2 ; number) :number{
                retrun n1 + n2
           }

Copy the code

6. An Array type

//Array declaration:
	// Type [] or Array < type >18350089047 13400505548

let arr : Number []  // Array of values

let arr: Array <Number>
Copy the code

7. The tuple type

Tuples, tuples are arrays of fixed length. (New TS)

let strArr :[string.string]

strArr=['hello'.'word'] // If the type is different, an error will be reported
Copy the code

8. Enum enumeration

In practice, some variables have only several possible values. For example, there are only two possible values for a person’s sex and only seven possible values for a week. Such special values in TS can be defined as enumerated types. Enumeration refers to enumerating the values of variables one by one, and the values of variables are limited to the range of listed values. To define a variable as an enumeration type, you can define an enumeration type name before stating that the variable is the enumeration type.

 
enum  arr{
    save, // Incrementing from 0 by default if no writing is done
    type./ / 1
    num=9.// If an assignment is made, the increment begins at the beginning of the assignment
    num2,/ / 10
}
console.log(arr.save);/ / 0
console.log(arr.type);/ / 1
console.log(num.type);/ / 9
console.log(num2.type);/ / 10
Copy the code

4. TS compilation

4.1 Compilation And Monitoring

TS does not currently run directly in the browser. It needs to be converted to a responsive JS file. The TSC xxx.ts command is used to compile, but we cannot execute this command every time we change the code, so we need to listen for the file.

// Command line code:
 tsc xxx.ts -w   // W watch
Copy the code

However, the previous writing method can only listen to a TS file, listening to multiple files can only open multiple terminals, which does not meet our daily development requirements. So we used the following approach when we actually developed.

  1. The tsconfig.json configuration file is first created in the root directory, either manually or automatically via TSC – -init
  2. Run TSC to compile all ts files in the directory
  3. Run tSC-m to listen for all TS files in the directory.

4.2 Tsconfig. json file Configuration

1.include

Used to define elements to be excluded.

tsconfig.json

{	
// Specifies which ts files to compile
	"include": ['./scr/**/*'.//** indicates any directory, * indicates any file]}Copy the code

2.exclude

Used to specify which files need not be compiled. If not specified, “exclude” by default excludes node_modules, BOWER_components, jSPM_packages, and

directories.

tsconfig.json 

{
	"exclude": ["./src/banner/**/*"]}Copy the code

3.extends

Inheritance. This is kind of like the introduction of JS. Json file extends is a top-level property in a tsconfig.json file (like compilerOptions, files, include, and exclude). The value of extends is a string containing a path to another file to inherit.

tsconfig.json

{
	"extends": '. / config/base '// Inherit the config/base.json file
}
Copy the code

4.files

Specifies a list of relative or absolute file paths.

Official website case {"files": [
        "core.ts"."sys.ts"."types.ts"."scanner.ts"."parser.ts"."utilities.ts"."binder.ts"."checker.ts"."emitter.ts"."program.ts"."commandLineParser.ts"."tsc.ts"."diagnosticInformationMap.generated.ts"]}Copy the code

5.compilerOptions (key)

The compile option is a very important and complex configuration option for configuration file weight.

Contains suboptions to configure compilerOptions.

Too many things to list all the details go to the website or configure TSC --init to check for 'compilerOptions':{"target" :"ES5".// Used to set the compiled ECMAscript version +
    "module":"es6".// Specify the modularity specification to use
    "lib": [].//lib is used to specify libraries to be used in the project
    "outDir":"./dist:".// Specifies the directory where the compiled file resides
    "outFile":"./dist/app.js"	// Merge the compiled code into a file
	"allowJs":true.// Whether to compile the JS file
	"removeComments":true		// Whether to remove comments
	"noEmit":false 				// No compiled files are generated
	"noEmitOnError":true		// Do not compile the file when there are errors
	
	"strict":true				// All strictly checked master switches this on the bottom four default to true recommended to true
	"alwaysStrict":false  		// Sets whether strict mode is turned on for compiled files
	"noImpLicitAny":true.// The implicit any type is not allowed.
	"noImplicitThis":true.// This is not allowed in undefined this methods. This :any must be specified in the argument
	"strictNullChecks":true   	// Check for null values. If null is possible, an error is reported
	     
}
Copy the code

4.3 WebPack Packs TS

The Node has been installed in advance.

1. Generate package.json from the command line in the project directory

npm init -y // Generate package.json file
// Install webPack and TS dependencies (skip those already installed)
npm install -D  webpack  webpack-cli typescript  ts-loader  

Copy the code

2. Add running Webpack in the scripts field of package.json

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
    },
Copy the code

3. Create the webpack.config.js configuration file in the project directory

// Import the Node path package
const path = require('path')

// Export all webPack configurations
module.exports = {

    // Specify the intersection file
    entry: "./src/index.ts".// Specify the directory where the package file resides
    output: {
        // Specify the directory to package the files
        path: path.resolve(__dirname, 'dist'),

        // The filename of the package
        filename: "bundle.js",},// Specify the module to use when webpack is packaged
    module: {

        // Specify the rules to load
        rules: [{// Specify the file in which the rule takes effect
                test: /\.ts$/.// Use ts-loader to package ts files
                use: "ts-loader".// Set files that do not need to be packaged
                exclude: /node_modules/}}}]Copy the code

4. Create the tsconfig.json configuration file in the root directory of the project

{
    // This is my own configuration
    "compilerOptions": {
        "module": "ES2015"."target": "ES2015"."strict": true}}Copy the code

**5. 打包编译只需运行 npm run bulid **

6. HTML – webpack – plugin plug-in

When the HTML page is displayed, we need to install this plug-in, which can dynamically generate HTML pages. (Previously, the HTML file was created manually and imported manually with script tags)

npm i -D html-webpack-plugin 
Copy the code

This is then configured in webpack.config.js

const htmlWebpackPlugin = require('html-webpack-plugin')
   // Export all webPack configurations
module.exports = {
   // Configure the WebPack plug-in
    plugins: [
        new htmlWebpackPlugin()
    ]
}
Copy the code

7. Webpack configuration module format

Sometimes, different modules need to import values from each other. For example, module A needs to import values from module B. However, if both modules are TS files, they cannot be imported (WebPack does not support TS module import by default).

You need to add fields to the webpack.config.js file:

module.exports = {

   // Set the format of the reference module
    resolve: {
        extensions: ['.ts'.'.js']  .ts and.js files are allowed to be modularized (such as importing and exporting modules).}}Copy the code

8. Install webPack’s Babel plugin

npm i -D @babel/core @babel/preset-env  babel-loader core.js
Copy the code

After installation, you need to configure Babel in webpack.config.js:

module.exports = {
	// Tell Webpack not to use arrow functions
	// Because webPack packs code blocks into a self-calling function that uses the arrow function internally
	// IE does not support this
	evironment: {arrowFunction:false
	},
	   // Specify the module to use when webpack is packaged
    module: {

        // Specify the rules to load
        rules: [{// Specify the file in which the rule takes effect
                test: /\.ts$/.// Use ts-loader to package ts files
                use: [
                    / / configuration Babel
                    {
                        // Specify the loader
                        loader: "label-loader"./ / set the Babel
                        options: {
                            // Set the predefined environment
                            presets: [[// Specify a plug-in for the environment
                                    "@babel/preset-env",
                                    {
                                        // Be compatible with browser versions
                                        targets: {
                                            "ie": "11"
                                        },
                                        // Specify the corejs version
                                        "corejs": "4".// Use corejs
                                        "useBuiltIns": "usage" // Load as needed}]]}},"ts-loader",].// Set files that do not need to be packaged
                exclude: /node_modules/}]}}Copy the code

5. The interface

An interface is similar to a class in that it is used to define a class structure. The class class is recommended first

Before the interface we define the type of an object

	type myType={
		name:string.// The difference between an interface and an interface can be declared repeatedly
		age:number
	}

// Now use the interface to define a class structure, which attributes and methods should be included in a class
// Interfaces can also be used as type declarations
// The interface name is {}
	interface myType{
		name:string.age:number
	}

	const obj:myType={
		name:"sss".age:"111"
	}
Copy the code

1. Note that none of the attributes in the interface can have actual values. Interfaces can only define the structure of the object.

interface myType{
		name:string.age:number
		sayHello:void  // All methods in the interface are abstract methods
	}
Copy the code

2. When defining a class, you can make it implement an interface. Implementing an interface is to make the class meet the requirements of the interface

interface myType{
		name:string.age:number
		sayHello:void  // All methods in the interface are abstract methods
	}

        // Implements the interface through implements
class MyClass  implements myType{
    name:string;
    constructor(name:string){
		this.name=name
    }
    
    sayHello(){
      console.log(  "Thank you for reading my notes.")}}Copy the code

6. Modifiers for the class attribute

TS can precede an attribute with a modifier

Attribute modifier role
static Properties that begin static become static properties (class properties) and can only be called by the class
readonly Represents a read-only property that can only be read but cannot be modified. Used in typescript.
public Default values, public properties, anyone can access them.
private Private properties, which can only be accessed from within a class and the programming specification generally starts with an _ underscore
protected Protected properties that can only be used and modified in the current class and subclasses of the current class.

6. The generic

Where generics work: We can use generics if the type of a function or class is ambiguous when we define it.

1. Use of generics in functions

1.Definition of generics in functions: < custom name >function fn < T > (a:T) :T{
    
						return a
			}     

2.The use of generics in functions1.Call directly without specifying a generic type. TS can automatically detect types (sometimes incorrectly)let result = fn ( a:10)

   2.Specifying generics (recommended)let result2=fn <srting>(a:'hello')
            
3.Generics can be defined in more than one functionfunction fn <L.V> (a:L,B:V) :L{
                console.log(a)
                console.log(B)
                return a,B
            }
			
			fnM<number.string> (a:1.B:"The Eight Turtles.")

4.Generic implementation interfaceCopy the code

2. Generics are used in classes

 class Person<T>{
	name:T;
	constructor(name:T){
	 	this.name=name
	}
}

const mc = new Person <string> (name:"The Eight Turtles.")
Copy the code