A comprehensive introduction to TypeScript

Table of contents

TS(TypeScript)

1. TS installation and configuration

2. The first TS program (example)

3. Configure automatic compilation

4. Variable declaration

5. Functions

6. Overload

7. class

8. Interface

9. Modular development


TS(TypeScript)

        The old JS is a weakly typed language, and a variable can store different types of data successively, which is extremely unreliable; and the old JS is an interpreted execution language, which is executed while interpreting, resulting in some low-level errors that cannot be checked and warned in advance; The requirements are not strict enough, and developers can write whatever they want, which is not convenient for large-scale project collaboration.

        TypeScript  is a superset of JavaScript, developed by Microsoft, supports the ECMAScript6 standard, and is designed to develop large-scale applications. TypeScript cannot be directly executed by the browser, but TypeScript can be compiled into JavaScript first, and then run on the browser or nodejs.

1. TS installation and configuration

        a. Install the TypeScript language compiler globally: enter npm i -g typescript at the cmd command prompt ; it only needs to be installed for the first time.

        b. After opening the project folder with vscode, right-click to open in the terminal, and enter tsc -init in the terminal (tsc is the compiler of the ts language, c is the meaning of compile, compile), and then it will be in the current project folder Generate  tsconfig.json  file; 

It saves the configuration required when compiling ts to js, ​​such as:

        target: "ES5", when compiling a ts file into a js file, compile it into an ES5 version, compatible with more browsers;

        module: "commenJS", the standard used for modular development in ts files in the future;

        strict: true, when compiling ts files to js files, strict mode is automatically enabled.

If tsc.ps1 error is reported:

        Search for powershell in the Windows start menu, right-click, and choose to run as an administrator;

        In the pop-up powershell window, enter: set-ExecutionPolicy RemoteSigned --> press Enter --> enter a --> press Enter.

2. The first TS program (example)

Create a .ts file 1_first.ts;

Open the command line window, enter tsc 1_first.ts, and then compile the ts file into a js file;

As shown above, the tsc compiler translates the content of the .ts file into an equivalent js file and saves it in the 1_first.js file with the same name next to the ts file;

        It can be found that many ts grammars written in ts files are omitted in js, because the checking of ts language occurs in the compilation phase, not the running phase; the special grammar written in ts is used in the compilation phase Yes, after compiling and running in the future, there is no need to recheck, so no special syntax is required.

Next, run the 1_first.js file with node.

3. Configure automatic compilation

        In vscode, select "Terminal" --> "Run Build Task" --> "tsc: monitor xxx" ; after the configuration is complete, just modify the ts file and save it, and it will automatically compile and create the .js file.

        In addition, you don’t need to enter the command to run the js file, first open the js file to be run, click the bug + triangle icon on the left --> run and debug --> nodejs, and you can see the execution result.

4. Variable declaration

        The old JS is a weakly typed language. A variable can store different types of data successively, which is unreliable; typescript stipulates that variables must be declared in the " : data type " format. As shown in the picture:

var/const/let 变量名:数据类型=初始值

//该变量只能保存规定类型的数据

        The data type of the variable can be boolean, number, string, array, and any, any means that any data type can be matched ; when the type is an array, there are two ways of writing:

let 数组名: 数据类型[]=[值1, 值2, ...]

let 数组名: Array<数据类型>=[值1, 值2,...]

        It should be noted that TypeScript is a strongly typed language. Even if it is useless when defining a variable for the first time  specify the data type of the variable, TypeScript will automatically use the variable value type when the variable is assigned for the first time as the data type of the current variable.

5. Functions

        When the function has a return value, it is written as follows:

function 函数名():返回值的类型{
  ...
  return 返回值
}

        If the function has parameters:

function 函数名(
  形参1:数据类型, 形参2:数据类型, ... ){
  ...
}

        If there are both formal parameters and a return value:

function 函数名(
  形参1:数据类型, 形参2:数据类型, ... 
  ):返回值类型 {
  ...
  return 返回值
}

        When default values ​​are required:

function 函数名(
  形参1:数据类型, 形参2:数据类型=默认值) {
  ... ...
}

        When the number of actual parameter values ​​is uncertain:

function 函数名(
  固定形参:数据类型, ...数组名:数据类型[]){
}

Example 1: Define a self-introduction function (using default values);

// 形参:数据类型=默认值(如果没有传参,默认为此值)
function intr(str: string = "这家伙有点懒,什么都没写。。。") {
  console.log(`自我介绍:${str}`);
}

intr("我是吕布,三国第一猛将!");
intr();

Example 2: Calculate the sum of any item (the number of actual parameter values ​​is uncertain);

function jisuan(ename: string, ...arr: number[]) {
  return `${ename}的总工资为:${arr.reduce((box, elem) => box + elem)}`;
}
console.log(jisuan("张飞", 10000, 200, 144, 5000));
console.log(jisuan("刘备", 14000, 2000, 544));

        The results of Example 1 and Example 2 are as follows:

6. Overload

        In the old js, overloading defines a function, and executes different logic in the function according to the parameters passed in;

        But in TS: first define multiple function declarations with the same name and different formal parameter lists, and do not implement the function body first,

function 函数名():void; 
function 函数名(形参:数据类型):void;  

//void代表这个函数,没有返回值
//如果函数有返回值,必须将void改为返回值的具体类型

        Second, define a function that can actually perform multiple tasks to support the multiple overloaded cases above.

function 函数名(){
  
}

Example: use overload to implement three payment methods;

// 先定义三种重载的情况
// void代表这个函数没有返回值
function pay(): void;
function pay(money: number): void;
function pay(card: string, pwd: string): void;

function pay(...arr: any[]) {
  if (arr.length == 0) {
    console.log(`手机支付`);
  } else if (arr.length == 1) {
    console.log(`微信支付`);
  } else {
    console.log(`刷卡支付`);
  }
}

pay(); //手机支付
pay(10000); //微信支付
pay("123456", "000"); //刷卡支付
//pay(123,456)  不符合最初定义的三种重载情况时直接报错

The result of the operation is as follows:

7. class

Definition of class type:

class 类型名{
   属性名1:数据类型=初始值;
   属性名2:数据类型=初始值;
 constructor(形参1:数据类型, 形参2:数据类型){
   this.属性名1=形参1;
   this.属性名2=形参2;
   }
   方法名():数据类型{ ... }
}

        Note: The attribute of class in TS must be defined in advance above the constructor and specify the data type, so that this. attribute name = assignment can be executed in the constructor.

For example: define the type of students, describe the unified structure of students;

class student {
  sname: string = "";
  sage: number = 0;
  constructor(sname: string, sage: number) {
    this.sname = sname;
    this.sage = sage;
  }
  intr(): any {
    console.log(`我是${this.sname},我今年${this.sage}岁。`);
  }
}
var zhang = new student("张飞", 52);
zhang.intr();
console.log(zhang);

The result of the operation is as follows:

        All members in a class can be accessed by "this.property name" or "object name.property name" whether they are in the class, in the subtype or globally; but if some data do not want to be accessed at will, you need to use Access control modifiers .

        An access modifier is a keyword that specifically modifies the available scope of a property or a method; the format is as follows:

Access Control Modifier Property Name  Data Type = Initial Value

Three types of access control modifiers:

(1) public public (default) , which means a class member that can be accessed by both the subtype and the outside of the class;

(2) protected is protected , which means that it can only be used within the scope of the parent-child type, and it is not available externally;

(3) private private , which means that it is only available within the class, and cannot be used by subtypes or outside.

Example: Use an example of a family managing money to illustrate the three types of access control modifiers;

class Father {
  public moneyPublic: string = "Father公开的钱";
  protected moneyProtected: string = "Father和Son的钱";
  private moneyPrivate:string="Father私有的钱";
  fatherPay() {
    console.log(`Father用${this.moneyPublic}给自己买了一包烟!`);
    console.log(`Father用${this.moneyProtected}给自己买了一块表!`);
    console.log(`Father用${this.moneyPrivate}给自己买了一身衣服!`);
  }
}
class Son extends Father {
  sonPay() {
    console.log(`Son用${this.moneyPublic}给自己买了一个玩具!`);
    console.log(`Son用${this.moneyProtected}给自己买了零食!`);
  }
}

var f1 = new Father();
var s1 = new Son();
f1.fatherPay();
s1.sonPay();

// 全局mother
console.log(`mother用${f1.moneyPublic}给自己买了一个包包!`);

The result of the operation is as follows:

8. Interface

        If you want developers to implement the program structure according to the architect's requirements, use the interface to standardize. The first is to define the interface:

interface I接口名{
  规定的属性名: 类型;
  规定的方法名(参数:数据类型):返回值;
}

        Next "implement the interface":

class 类型名 implements I接口名{
  //必须包含接口中规定的属性和方法
}

Example: using interface specifications to realize aircraft flight;

interface IPlane {
  x: number;
  y: number;
  fly(): void;
}
class Plane implements IPlane {
  x: number = 0;
  y: number = 0;
  score: number = 0;
  constructor(x: number, y: number, score: number) {
    this.x = x;
    this.y = y;
    this.score = score;
  }
  fly(): void {
    console.log(`飞到x=${this.x},y=${this.y}的位置`);
  }
  getScore(): void {
    console.log(`击落敌机得${this.score}分`);
  }
}
var p = new Plane(100, 20, 20);
p.fly();
p.getScore();
console.log(p);

The result of the operation is as follows:

9. Modular development

        Modular development means that which file wants to use the content of another file, just import it directly.

        When exporting only one interface or type:

//先创建类型/接口

//导出
export default 类型名/接口名

//引入
import 类型名 from “相对路径”

        To export multiple interfaces or types:

//先创建多个类型/接口

//导出
export { 类型名, … }

//引入
import { 类型名, … } from “相对路径”

Guess you like

Origin blog.csdn.net/weixin_53072519/article/details/120485064