TS usage

Time:2022-6-5

TS learning use

1、 TS environment setup

1.ts introduction

Typescript is a superset of JavaScript. On the basis of JS, restrictions on variable types are added

2. environment

1. install node:https://nodejs.org/dist/v16.1…
2. install TS compiler typescript using package manager

npm install -g typescript

Compile run:

// tsc =====> typescript compiler

//Compile compiles the specified TS into js,tsc hell. TS -w can complete the automatic recompilation of modified files
tsc hello.ts

//Run the compiled js
node hello.js

3. you can use TS node to compile and run TS at one time

//Installing TS node
npm install -g ts-node

//Run TS
ts-node hello.ts

2、 Basic types of TS

1. basic usage of type declaration:

let a: number;
let b: string = "hello";
function fn(x:number, y:string):void{
    console.log(x, y);
}

2. common types

Number, string, boolean type:

let a:string;
let b:boolean;
function fu():number{
    return 1;
}

Literal type:

//Directly use literal quantity for type declaration, which is equivalent to constant when used
//You can use | to connect multiple types
let sex: "male" | "female";
sex = 'male';

Any type:

//Any type is equivalent to no type restriction
let d: any;    //  Show any type
let m;        //  Implicit any type

Unknown type:

let s: string;

//Unknown is actually type safe any
//Variables of unknown type cannot be directly assigned to variables of other types
let e: unknown = "hello";

//Assign unknown to another type
//Method 1: type judgment
if(typeof e === "string"){
    s = e;
}

//Method 2: type assertion
// s = (<string>e);
s = e as string;

Void and never:

//Void return value is null
function fn():void{
    return undefined||null;
}

//Never has a return value. It is often used in functions that report errors
function fn2():never{
    throw new Error('error');
}

Object type:

//Object declaration 1:
let a: object; //  Can be any type of object, generally not applicable

//Object declaration 2:
Let b: {// object type declaration, including attribute restrictions
    name: string,
    age? :  number        // ?  Indicates that the change attribute is optional
};

b = {
    name: 'jiangjiangwa',
    age: 18
}

//Object declaration III:
let c:{
    name: string,

    //Any string attribute name, any attribute value of any type
    [x: string]: any
}

Function structure type declaration:

//(formal parameter: type, formal parameter: type) = > return value type
let f :(arg1:number,arg2:number)=>number

f = function(n1,n2):number{
    return n1+n2;
}

Array type:

//Represents an array of numbers
let a:number[];
let b:Array<number>;

Tuple fixed length array:

let h:[123,string];
h = [123, "world"];

Enum enumeration type:

enum Gender {
    Male,
    Female,
}
  
console.log(Gender)
let i: { name: string; gender: Gender };
i = {
  Name: "Sunwukong",
  gender: Gender.Male, // 'male'
};

Union type:

let a:number|string;
a = 1;

let b : {name:string}&{age:number};

b = {
    name:'jiangjiangwa',
    age:18
}

Alias for type

type myType = string | number;

let k:myType = 'hello';

3、 TS compilation options

Initialize the TS compilation configuration file tsconfig json

tsc --init    

Use tsconfig JSON, you can batch compile all TS files of the entire project
//TSC directly compiles all TS files

//TSC -w compile all TS files and monitor all TS files

tsconfig. JSON configuration parameter description:

{
  /* 
  tsconfig. JSON is the configuration file of the TS compiler. The TS compiler reads the file and compiles the TS file according to the configuration of the file.
    "Include": used to specify which TS files need to be compiled
      Path: * * recursively match any subdirectory
            *Represents any file
            ?   Match an arbitrary character (excluding the directory separator

   */
  "include": ["./src/**/*.ts", "./src/**/*.js", "./main.ts"],
  //"Exclude": [". /node_modules"], // there is a default value
  "compilerOptions": {
    //Target is used to specify the ES version to which TS is compiled
    "target": "ESNext", //ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext
    "Module": "es2015", // specifies to compile as a modular specification

    //Lib is used to specify which libraries need to be included in the compiled JS. Multiple libraries can be specified
    //"Lib": ["DOM", "ES6"] // unchanged by default

    "Outdir": "./dist", // specify the output directory of the compiled JS file

    //After setting the outfile, all the codes in the global scope are merged into a unified JS file, which is usually completed using the packaging tool
    // "outFile": "./dist/bindle.js",

    //Whether to compile the JS file. The default value is false
    "allowJs": true,

    //Whether to check the syntax of the JS code. The default is false. You need to check the syntax of the JS code in tsconfig Set "allowjs" in JSON: true
    "checkJs": true,

    "Removecomments": false, // whether to remove comments. The default value is false

    //The compiled JS file is not generated. The default value is false But when you only need to check the syntax of TS, use
    "noEmit": false,

    //All main switches subject to strict inspection
    "strict":true,

    //When an error occurs, the compiled file is not generated. The default value is false
    "noEmitOnError": true,

    "Alwaysstrict": true, // whether strict mode is enabled. The default is false. When modular syntax is used, strict mode is enabled by default

    //Implicit any type is not allowed. The default is false
    "noImplicitAny": true,

    //This of ambiguous type is not allowed
    "noImplicitThis": true,

    "Strictnullchecks": false, // whether to enable strict null value checking. The default value is false
  
  } 
}

5、 Object oriented

1. use of class

//Use the class keyword to define a class
/* 
Describe the attributes (instance attributes, static attributes) and methods of the class
When assigning values to static methods or real column attributes of a class, they need to be restricted
 */

class Person {
  //Static properties
  Static readonly county: string = "China";

  //Instance properties
  name: string = "default";
  age = 18;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  //Real column method
  //   say: (a: number, b: number) => void = function (a, b) {
  //     console.log(a + b);
  //   };
  say(a: number, b: number): number {
    return a + b;
  }
}

const person = new Person("John", 30);

Extensions uses:
The open closed principle (OCP) is closed for modification and open for extension.

class Animal {
    name: string;
    age: number;
    constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
    }
    say() {
      console.log("I am a animal");
    }
  }

  class Dog extends Animal {
    constructor(name: string, age: number) {
      super(name, age);
    }
  }

  class Cat extends Animal {
      say(): void {
          console.log('miao miao miao')
      }
      //If the constructor method is not overridden, the created instance will call the constructor of the parent class
  }

Cat.prototype.__proto__ = Animal.prototype

Abstract class abstract:

(function () {
    //Cannot be used to create a real column. It is specially used to inherit classes
    //You can add abstract methods
  abstract class Animal {
    name: string;
    age: number;
    constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
    }

    //An abstract method can only be defined in an abstract class. Subclasses must implement the method
    abstract say(): void;
  }

  class Dog extends Animal {
    constructor(name: string, age: number) {
      super(name, age);
    }
    say(): void {
        console.log('wang wang wang')
    }
  }

  class Cat extends Animal {
    say(): void {
      console.log("miao miao miao");
    }
    //If the constructor method is not overridden, the created instance will call the constructor of the parent class
  }
})();

Interface

const obj: myInterface = {
    name: "John",
    age: 30,
    Gender: "male",
    say() {
      console.log("jiang");
    },
  };
  console.log(obj);

  //Structure is used to define the structure of a class. It can also be used as a type declaration
  //Repeatable declaration, superposition of type restrictions, and all methods in the interface are abstract methods
  //To implement an interface is to meet the requirements of the interface
  interface myInterface {
    name: string;
    age: number;
  }

  interface myInterface {
    gender: string;
    say(): void;
  }

  class Person implements myInterface {
    name: string;
    age: number;
    gender: string;

    constructor(name: string, age: number, gender: string) {
      this.name = name;
      this.age = age;
      this.gender = gender;
    }
    say(): void {
      throw new Error("Method not implemented.");
    }
  }
  console. Log (new person ('jiang', 18,' male ');

Attribute encapsulation:

(function () {
  class Person {
    private _name: string;

    get name(): string {
      return this._name;
    }
    set name(value: string) {
      If (this.name.startswith ("Zhang"){
        this._name = value;
      } else {
        this._ Name = "Zhang" + value;
      }
    }
    age: number;
    constructor(name: string, age: number) {
      this._name = name;
      this.age = age;
    }
  }

  let p = new Person("John", 30);
  console.log(p);

  p.name = "Tom";
  p.age = 10;
  console.log(p);
})();

Abbreviation of class+ attribute encapsulation:

class Dog {
    constructor(public name: string, private age: number) {}

    //Equivalent to
    // public name: string;
    // private age: number;
    // constructor(name: string, age: number) {
    //   this.name = name;
    //   this.age = age;
    // }
  }

Generic:

function fn<T>(a: T): T {
  return a;
}

//No generics specified, type inference used
console.log(fn("1"));
console.log(fn<number>(19));

/* 
    When defining functions or classes, you can use generics if the type is ambiguous
    Defines a variable that represents a type
 */

interface Inter {
  length: number;
}

/* 
Generic restrictions, which must comply with interface type restrictions
T extends inter indicates that generic t must be an inter implementation class (subclass)
 */
function fn2<T extends Inter>(a: T): number {
  return a.length;
}

fn2("1");