1. Preparatory work

1.1 Introduction to TypeScript

  1. TypeScript is a superset of JavaScript types that can be migrated to pure JavaScript
  2. TypeScript runs in any browser, on any computer, and on any operating system. It is developed and open-source by Microsoft

1.2 TypeScript and JavaScript

  1. TypeScript is a superset of JavaScript, a language built on top of JavaScript
  2. TypeScript extends JS by introducing the concept of types and adding many new features
  3. TS code cannot be run directly. It needs to be compiled into JS code by a compiler and then executed by a JS parser
  4. TS is fully JS compatible; in other words, any JS code can be used directly as TS
  5. Compared with JS, TS has static typing, stricter syntax, and more powerful functions

1.3 Advantages of TypeScript

  1. TS checks code before it is executed, reducing the chance of runtime exceptions
  2. TS can be compiled into any version of JS code, which can effectively solve the compatibility problem of different JS operating environment
  3. The same function, TS code is larger than JS, but with TS code structure is clearer, variable type is more clear, in the later code maintenance, TS is far better than JS,

1.4 TypeScript development environment construction

  1. Download Node.js (stable version recommended)
  • A 64 – bit
  • 32 –
  1. After the installation, run the node -v command to check the node version. If the version information is displayed, the node is successfully installed
  2. Use NPM to install typescript globally. Type NPM i-g typescript on the command line and then type TSC on the command line. If version information and operation prompts are displayed, the installation is successful
  3. Create a simple ts file with the suffix.ts
  4. In the command line window to compile into the directory, enter the commandtsc helloTS.tsWhen you’re done, you can see the JS file that compiled successfullyThe TypeScript environment is now set up

2 Basic Types

2.1 Type Declaration

  1. Type declaration is a very important feature of TS, and also the most important point of TS transformation of JS

  2. Type declarations allow you to specify the types of variables (parameters, parameters) in TS

  3. When assigning a value to a variable after specifying a type, the TS compiler automatically checks whether the value matches the declaration. If so, the value is assigned; otherwise, an error is reported

  4. In short, a type declaration sets the type of a variable, causing the variable to store a value of some type

  5. grammar

    Automatic type judgment

    • TS has an automatic type determination mechanism
    • When a variable is declared and assigned simultaneously, the TS compiler automatically determines the type of the variable
    • So when variables and declarations are made automatically, you can omit type declarations
    letVariable: type;letVariable: type = value;function fn(Parameter: type, parameter: typeType) :{... }Copy the code
    // Declare a variable a and specify its type as number
    let a:number;
    
    // Set the type of a to number. The value of a can only be a number
    a=22;
    a=33;
    // a="hello" // this line of code will report an error because variable A is of type number and cannot be assigned to a string
    
    let b: string;
    b = 'hello';
    // b = 123; // This line of code will report an error because variable B is of type string and cannot be assigned a number
    
    // Assign the value directly after declaring the variable
    let c:boolean = false;
    
    TS can automatically type check variables if they are declared and assigned at the same time
    let d = false;
    // d=" ABC "// this is an error
    d = true;
    
    // a function in javascript does not take into account the type or number of arguments
    // function sum(a, b){
    // return a + b;
    // }
    
    // console.log(sum(123, 456)); / / 579
    // console.log(sum(123, "456")); / / "123456"
    
    // If the parameter type is number, the return value type is also number
    function sum (a:number,b:number) :number{
        return a+b;
    }
    let result = sum(123.456)
    console.log(result);
    
    Copy the code

2.2 Basic Types and Types

type example describe
number 1, 33, 2.5 Any Numbers
string ‘hi’, “hi”, hi Arbitrary string
boolean True, false, Boolean value true or false
literal In its own right The value of the constraint variable is the value of the literal
any * Any type
unknown * Type safe any
void Null value (undefined) No value (or undefined)
never There is no value It can’t be any value
object {name:’ Sun Wukong ‘} Any JS object
array [1, 2, 3] Arbitrary JS array
tuple (4, 5) Element, TS new type, fixed length array
enum enum{A, B} Enumeration, new type in TS
  • number

    let decimal: number = 6;
    let hex: number = 0xf00d;
    let binary: number = 0b1010;
    let octal: number = 0o744;
    let big: bigint = 100n;
    Copy the code
  • boolean

    let isDone: boolean = false;
    Copy the code
  • string

    let color: string = "blue";
    color = 'red';
    
    let fullName: string = `Bob Bobbington`;
    let age: number = 37;
    let sentence: string = `Hello, my name is ${fullName}.I'll be ${age + 1} years old next month.`;
    Copy the code
  • literal

    A literal can also be used to specify the type of a variable. A literal can be used to determine the value range of a variable

    let color: 'red' | 'blue' | 'black';
    let num: 1 | 2 | 3 | 4 | 5;
    Copy the code
  • any

    let d: any = 4;
    d = 'hello';
    d = true;
    Copy the code
  • unknown

    let notSure: unknown = 4;
    notSure = 'hello';
    Copy the code
  • void

    let unusable: void = undefined;
    Copy the code
  • never

    function error(message: string) :never {
      throw new Error(message);
    }
    Copy the code
  • Object specifies the type of the object directly in {}

    let obj: object = {};
    Copy the code
  • array

    let list: number[] = [1.2.3];
    let list: Array<number> = [1.2.3];
    Copy the code
  • tuple

    let x: [string.number];
    x = ["hello".10]; 
    Copy the code
  • enum

    num Color {
      Red,
      Green,
      Blue,
    }
    let c: Color = Color.Green;
    
    enum Color {
      Red = 1,
      Green,
      Blue,
    }
    let c: Color = Color.Green;
    
    enum Color {
      Red = 1,
      Green = 2,
      Blue = 4,}let c: Color = Color.Green;
    Copy the code
  • Types of assertions

    In some cases, the type of the variable is clear to us, but not to the TS compiler. In this case, we can tell the compiler the type of the variable using a type assertion, which can take two forms:

    • The first kind of

      let someValue: unknown = "this is a string";
      let strLength: number = (someValue as string).length;
      Copy the code
    • The second,

      let someValue: unknown = "this is a string";
      let strLength: number = (<string>someValue).length;
      Copy the code
// Type declarations can be made directly with literals
let a:10
a = 10

/ / | can be used to connect multiple types (combined type)
let b:"male"|"female";
b = "male";
b = "female"
// b = "hello" // error because hello does not belong to the above two values



let c: boolean | string;
c = true;
c = 'hello'

// Any indicates any type. Setting the type of a variable to any disables TS type detection for the variable
// When using TS, do not use any type
// let d: any;

If no type is specified, the TS parser automatically determines the type of the variable to be any (implicit any).
let d;
d = 10;
d = 'hello';
d = true;

// unknown Indicates the value of the unknown type
let e: unknown;
e = 10;
e = "hello";
e = true;

let s:string;

// d is of type any and can be assigned to any variable
// s = d;

e = 'hello';

//s = e // Error because the type of s is a string and the type of e is unknown

// Unknown is actually a type-safe any
// Variables of unknown type cannot be directly assigned to other variables
if(typeof e === "string") {// Can only be assigned if the type is string
    s = e;
}


// Type assertion, which can be used to tell the parser the actual type of a variable
/* * syntax: Both * variables as types * < type > variables * both uses have the same effect * */
s = e as string;
s = <string>e

// void is a function that returns no value
function fn() :void{}// never: the result is never returned
function fn2() :never{
    throw new Error('Wrong! ');
}
Copy the code
//object represents a JS object
let a :object;
a={}
a = function(){};

//{} is used to specify which attributes an object class can contain
// Syntax: {attribute name: attribute value, attribute name: attribute value} Be consistent with the declared type and number
// Add an attribute after it. Indicates that the property is optional
let b:{name:string,age? :number};
b={name:'page'.age:18}
b={name:Sun Wukong}

//[XXX: type]:any indicates an attribute of any type
// I only need a name attribute of type string. I don't care about the rest
let c:{name:string,[proName:string] :any};
c={name:'Pig Eight Quit'.a:1.c:'male'}

/** * Uses the arrow function to set the declared type of the function structure * syntax: (parameter: type, parameter: type) => return type ** /

// limit d to a function that takes two parameters of type number and returns number
let d:(a:number,b:number) = > number;
d = function(num1,num2) :number{
    return num1+num2
}

Type [] * Array< type > * */
// String [] represents an array of strings
let e:string[]

let f:number[]

let g:Array<number>

e=['ds'.'a']
g=[1.3.6.9.6]

/** * tuple * tuple: fixed length array */

let h:[string.string];
h=['hello'.'world']
//h=['hello','world','!'


/** * enum enum ** /

// Define an enumeration type
enum Gender{
    Male,
    Female
}
let i:{name:string.gender:Gender}
i = {
    name:Sun Wukong.gender:Gender.Male
}

// console.log(i.gender === Gender.Male);

//& indicates the same time
let j :{name:string} and {age:number}

// An alias for the type to simplify the use of the type
// type myType = string;
// let m :myType;

type myType = 1|2|3|4|5
let k : myType;
let l : myType

Copy the code

3 Compilation Options

3.1 Automatically Compiling files

  1. When compiling a file, using the -w command, the TS compiler automatically watches for changes to the file and recompiles the file when it sends changes
  2. Instructions:tsc xxx.ts -w

3.2 Automatically compile the entire project

  1. If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files. To use the TSC command directly, you must create a tsconfig.json configuration file in the root directory of the project
  2. Tsconfig. json is a JSON file. After adding the configuration file, you only need TSC command to complete the compilation of the entire project
  3. Configuration options:
  • include

    • Defines the directory where you want the files to be compiled

    • Default value: [“**/*”]

    • The sample

      "include": ["src/**/*"."tests/**/*"]
      // All files in the SRC directory and tests directory will be compiled. Note where SRC is located
      Copy the code
  • exclude

    • Define the directories that need to be excluded

    • Default: [“node_modules”, “boWER_components “,” jSPM_packages “] default: [“node_modules”, “bower_components”, “jSPM_packages “]

    • The sample

      "exclude": ["./src/hello/**/*"]
      // SRC files in the hello directory will not be compiled
      Copy the code
  • extends

    • Define inherited configuration files

    • Example:

      "extends": "./configs/base"
      // The current configuration file automatically contains all the configuration information in base.json in the config directory
      Copy the code
  • Files (rarely used)

    • Specifies a list of files to compile, used only when there are fewer files to compile

    • The sample

      "files": [
          "core.ts"."sys.ts"."types.ts"."scanner.ts"."parser.ts"."utilities.ts"."binder.ts"."checker.ts"."tsc.ts"
        ]
      // The files in the list are compiled by the TS compiler
      Copy the code
  • CompilerOptions (the most important and complex)

    • Compile options are important and complex configuration options in configuration files

    • Contains suboptions to configure compilerOptions

    • Project Options:

      1. Target: Sets the target version for ts code compilation
      • Optional values: [When an incorrect value is entered, the compiler prompts what options are available]

        ES3 (default), ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext

      • Example:

        // The ts code we wrote will be compiled into the ES6 version of js code
        "compilerOptions": {
            "target": "ES6"
        }
        Copy the code
      1. Lib: Specifies the library (host environment) that the code will contain at runtime
      • Optional values: ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext, DOM, WebWorker, ScriptHost……

      • Example:

        "compilerOptions": {
            "target": "ES6"."lib": ["ES6"."DOM"]."outDir": "dist"."outFile": "dist/aa.js"
        }
        Copy the code
      1. Module: Sets up the modular system used by compiled code
      • Optional value: ‘none’, ‘commonjs’,’ amd ‘, ‘the system’, ‘umd’, ‘es6’, ‘es2015’, ‘es2020’, ‘esnext’

      • Example:

        "compilerOptions": {
            "module": "CommonJS"
        }
        Copy the code
      1. OutDir: directory where compiled files reside
      • By default, compiled JS files are located in the same directory as ts files. Setting outDir can change the location of compiled files

      • Example:

        // The compiled JS file will be generated in the dist directory
        "compilerOptions": {
            "outDir": "dist"
        }
        Copy the code
      1. OutFile: Compiles all files into a JS file
      • By default, all code written in the global scope is merged into a JS file, and modules are merged together if the Module specifies None, System, or AMD

      • Example:

        "compilerOptions": {
            "outFile": "dist/app.js"
        }
        Copy the code
      1. RootDir: Specifies the root directory of the code
      • By default, the directory structure of compiled files takes the longest public directory as the root directory. You can specify the root directory manually using rootDir

      • Example:

        "compilerOptions": {
            "rootDir": "./src"
        }
        Copy the code
      1. AllowJs: no compilation of js files. The value is true or false
      2. CheckJs: Whether to check the JS file
      • Example:

        "compilerOptions": {
            "allowJs": true."checkJs": true
        }
        Copy the code
      1. Other:
      • RemoveComments: whether to removeComments. The default value is false
      • NoEmit: does not compile the code, i.e. generates a compiled file. The default value is false
      • SourceMap: specifies whether to generate sourceMap. Default value: false
      1. Strict inspection
        • Strict: all strict checks are enabled. The default value is true. If this parameter is set, all strict checks are enabled
        • AlwaysStrict: Always compile code in strict mode
        • NoImplicitAny: Disables the implicit any type
        • NoImplicitThis: Disallows this of undefined type
        • StrictBindCallApply: Strictly checks bind, call, and apply parameter lists
        • StrictFunctionTypes: Strictly checks the types of functions
        • StrictNullChecks: strictNullChecks
        • StrictPropertyInitialization: strict check attribute initialization
      2. Additional inspection
        • NoFallthroughCasesInSwitch: check switch statement contains the correct break
        • NoImplicitReturns: Checks that the function has no implicit return value
        • NoUnusedLocals: Checks for unused local variables
        • NoUnusedParameters: Checks the unused parameters
      3. Use advanced
      • AllowUnreachableCode: Checks unreachable codes

        Optional: true, ignoring unreachable code

        False: Unreachable code raises an error

      • NoEmitOnError: does not compile if there is an error. Default value: false

4 Configure TS using webPack

  1. TS can also be used in conjunction with build tools, which are often used to package code during actual development

  2. steps

    1. Initialize the project

      Go to the root directory of the project and run NPM init -y to create the package.json file

    2. Download the build tool: NPM I -d webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin

      7 packages installed:

      • Webpack: Build tool Webpack
      • Webpack-cli: Command line tool for Webpack
      • Webpack-dev-server: development server for Webpack
      • Typesript: TS compiler
      • Ts-loader: TS loader used to compile TS files in webpack
      • Html-webpack-plugin: HTML plug-in in webpack, used to automatically create HTML files
      • Clean-webpack-plugin: A clean plug-in in webpack that cleans the directory first with each build
    3. The configuration file webpack.config.js that creates webpack in the root directory

      // Import a package
      const path = require("path");
      // Introduce HTML plugins
      const HTMLWebpackPlugin = require('html-webpack-plugin')
      // Introduce the clean plug-in
      const {CleanWebpackPlugin} = require('clean-webpack-plugin')
      
      // all configuration information in webpack is written in module.exports
      module.exports = {
          // Specify the entry file
          entry:"./src/index.ts".// Specify the directory where the package file resides
          output: {// Specify the directory where the package file resides
              path:path.resolve(__dirname,'dist'),
              // The packaged file name
              filename:'bundle.js'
          },
          // Specify the module to use when webpack is packaged
          module: {// Specify the rules to load
              rules:[
                  {
                      //test Specifies the file in which the rule takes effect and writes the regular expression
                      test:/\.ts$/.// Which loader to use
                      use:'ts-loader'.// Files to be excluded
                      exclude:/node-modules/}},plugins: [new CleanWebpackPlugin(),
              new HTMLWebpackPlugin({
                  // title:' Just a custom title '
                  template:'./src/index.html'})].// Set the reference module
           resolve: {extensions: ['.ts'.'.js']},mode:'development'.// Development mode
         
      }
      Copy the code
    4. Tsconfig. json is created in the root directory and can be configured according to your needs

      {
          "compilerOptions": {
              "target": "ES2015",
              "module": "ES2015",
              "strict": true
          }
      }
      Copy the code
    5. Modify package.json to add the following configuration

      {... A little..."scripts": {
          "build": "webpack"."start":"webpack server --open chrome.exe"},... A little... }Copy the code
    6. Create the TS file under SRC and run NPM run build on the command line to compile the code, or run NPM start to start the development server

5 Babel

After a series of configurations, TS and WebPack have been combined. In addition to WebPack, Babel is often used to transform code to make it compatible with more browsers. Following these steps, Babel is introduced into the project.

  1. Install dependency packages:

    • Command: NPM I -d @babel/ core@babel /preset-env babel-loader core-js

    • A total of 4 packages are installed, which are:

      1) @babel/core: Babel’s core tools

      2) @babel/preset-env: Preset environment for Babel

      3) @babel-loader: loader for Babel in webpack

      4) core-js: Core-js is used to make older browsers support the new ES syntax

  2. Modify the webpack.config.js configuration file

    . A little...// Specify the rules to load
            rules:[
                {
                    //test Specifies the file in which the rule takes effect and writes the regular expression
                    test:/\.ts$/.// Which loader to use
                    use:[
                        / / configuration Babel
                        {
                            // Specify the loader
                            loader:"babel-loader"./ / set the Babel
                            options: {// Set the predefined environment
                                presets:[
                                    [
                                        // Specify a plug-in for the environment
                                        "@babel/preset-env".// Configuration information
                                        {
                                            // Be compliant with standards
                                           targets: {
                                               // Compatible version
                                               "chrome":"58"."ie":"11"// IE11 does not support the Promise syntax, so Corejs automatically converts promises during packaging
                                           },
                                           // Specify the version of Corejs
                                           "corejs":"3".// Specify the corejs mode. "Usage" indicates loading on demand
                                           "useBuiltIns":"usage"}]]},},'ts-loader'].// Files to be excluded
                    exclude:/node-modules/}]... A little...Copy the code

    Note that if you want to be compatible with IE11, you may have problems with arrow functions, so add them to the Output of webpack

    // Tell Webpack not to use arrows
            environment: {arrowFunction: false
            },
    Copy the code
  3. Once WebPack is configured, the files compiled using TS will be processed by Babel again, making the code available directly in most browsers. You can also specify the browser version to be compatible with under the Targets configuration option

6 Object Oriented

6.1 introduction

The object oriented section is similar to ES6, with the addition of type restrictions, just as a review

Object orientation is a very important idea in programs. In short, all operations in programs need to be done through objects.

For example:

  • To manipulate the browser, use the Window object
  • To manipulate a web page, use the Document object
  • The action console uses the Console object

Everything goes through objects, so called object orientation, so what exactly is an object? This is to talk about what the program is, the essence of the computer program is the abstraction of real things, the antonym of abstraction is concrete, for example: a photo is the abstraction of a concrete person, a car model is the abstraction of a concrete car and so on. Programs are also abstractions of things, in which we can represent a person, a dog, a gun, a bullet, and so on. An object becomes an object in a program.

In the program, all objects are divided into two parts: data and functions. For example, people’s name, gender, age, height and weight belong to data. People can talk, walk, eat and sleep, which belong to human functions. Data in objects are called properties, and functions are called methods. So in short, in a program everything is an object.

6.2 Class (Class)

To be object oriented and manipulate objects, you have to own them in the first place, so the next problem is how to create them. To create an object, you must first define the class, the class can be understood as object model, can according to the class to create specific types of objects in the program, for example: the Person class to founder of objects, create a Dog through Dog class object, through the Car class to create objects, different class can be used to create a different object.

  1. Define the class:

    classThe name of the class{attribute name: type;constructor(Parameter: Type){
    		this. Attribute name = parameter; } Method name (){.... }}Copy the code
    Use the class keyword to define a class
    The /* * object contains two main parts: * properties * methods * */
    class Person{
        /** * const per = new Person(); * * Attributes that start static are static attributes (class attributes) and can be accessed directly through class creep * * Person.age * * Readonly letters indicate that a read-only property cannot be modified */
    
        // Define instance attributes
        //readonly name:string = 'Sun Wukong ';
    
        name = Sun Wukong
    
        // Use the static keyword before attributes to define class attributes (static attributes)
        static readonly age:number = 18
        age = 18
    
        // Define the method
        // if the method starts static, it is a class method and can be called through the class
        sayHello(){
            console.log("Hello TS"); }}const per = new Person();
    console.log(per);
    console.log(per.name,per.age);
    
    console.log(Person.age);
    
    
    per.name = 'tom'
    console.log(per.name);
    
    per.sayHello()
    
    Copy the code
  2. The constructor

    class Dog{
        name:string;
        age:number;
        The constructor function is called when the object is created
        constructor(name:string,age:number){
            In the instance method, thi is the current instance
            // In the constructor, the current object is the currently created object
            // You can use this to add attributes to a newly created object
            this.name = name
            this.age = age;
        }
        bark(){
            console.log(this.name); }}const dog1 = new Dog('black'.4);
    const dog2 = new Dog('white'.2)
    
    console.log(dog1);
    console.log(dog2);
    
    dog1.bark()
    dog2.bark()
    Copy the code

6.3 Object-oriented features

  1. encapsulation
  • An object is essentially a container for properties and methods. Its main function is to store properties and methods, which is called encapsulation

  • By default, the properties of an object can be modified at will. To ensure data security, the permission of the properties can be set in TS

  • Read-only property (readonly) : If you add a readonly to the property declaration, the property becomes read-only and cannot be modified

  • TS attributes have three modifiers:

    • Public (default), which can be modified in classes, subclasses, and objects
    • Protected, which can be modified in classes and subclasses
    • Private, which can be changed in the class
  • Example:

    • public

      class Person{
          public name: string; // Write or write nothing is public
          public age: number;
      
          constructor(name: string, age: number){
              this.name = name; // Can be changed in the class
              this.age = age;
          }
      
          sayHello(){
              console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
          constructor(name: string, age: number){
              super(name, age);
              this.name = name; // Subclasses can be modified}}const p = new Person(Sun Wukong.18);
      p.name = 'Pig Eight Quit';// Can be modified by object
      Copy the code
    • protectd

      class Person{
          protected name: string;
          protected age: number;
      
          constructor(name: string, age: number){
              this.name = name; // It can be modified
              this.age = age;
          }
      
          sayHello(){
              console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
      
          constructor(name: string, age: number){
              super(name, age);
              this.name = name; // Subclasses can be modified}}const p = new Person(Sun Wukong.18);
      p.name = 'Pig Eight Quit';// Cannot be modified
      Copy the code
    • protect

      class Person{
          private name: string;
          private age: number;
      
          constructor(name: string, age: number){
              this.name = name; // It can be modified
              this.age = age;
          }
      
          sayHello(){
              console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
      
          constructor(name: string, age: number){
              super(name, age);
              this.name = name; // Cannot be modified in subclasses}}const p = new Person(Sun Wukong.18);
      p.name = 'Pig Eight Quit';// Cannot be modified
      Copy the code
  • Attribute accessor

    • For properties that do not want to be arbitrarily modified, you can set them to private

    • But making it private directly will make it impossible to modify its properties through objects

    • So we can define a set of methods in a class that read and set properties, called accessors for properties

    • The methods that read properties are called setter methods, and the methods that set properties are called getter methods

    • Example:

      (function (){
          // Define a class that represents a person
      class Person{
          //TS can add modifiers to attributes
          /** * public: modified properties can be accessed (modified) from anywhere default * private: private properties can only be accessed (modified) from within the class * -- Private properties can be accessed externally by adding methods to the class * protected: protected properties. */ can only be accessed (modified) in the current class and subclasses of the current class
          private name:string;
          private age:number;
          constructor(name:string , age:number){
              this.name = name;
              this.age =age
          }
      
          /* * * Getter methods are used to read properties * setter methods are used to set properties * -- they are called accessors for properties */
          
          // Define a method to get the name attribute
      /* getName(){ return this.name; } setName(value:string){this.name = value; GetAge (){return this.age; SetAge (value:number){if(value >= 0){this.age = value} */
      
          //TS getters and setters, per.getName, per.getName, per.getName, per.getName, per.getName
          get Name() {console.log("Get name() executed");
              return this.name
              
          }
          set Name(value) {this.name = value
          }
      
          get Age() {return this.age;
           }
      
           
           set Age(value:number) {// Check whether the age is legal
               if(value >= 0) {this.age = value
              }
           } 
          
      }
      const per = new Person("Sun Wukong".18)
      // console.log(per.getName());
      console.log(per.Name);// The get method is actually called
      console.log(per.Age);
      
      per.Name = 'Pig Eight Quit'
      console.log(per.Name);
      per.Age = -33
      
      console.log(per.Age);/ / don't change
      
      class A{
          protected num: number;
      
          constructor(num: number) {
              this.num = num; }}class B extends A{
      
          test(){
              console.log(this.num); }}const b = new B(123);
      console.log(b);
      // b.num = 33; // Cannot access
      
      
      /* class C{ name: string; Constructor (name: string, age: number) {this.name = name; this.age = age; }} * /
      
      class C{
      
          // Attributes can be defined directly in constructors
          constructor(public name: string.public age: number){}}const c = new C('xxx'.111);
      
      console.log(c); }) ()Copy the code
  • Static attributes

    • Static properties (methods), also known as class properties. You don’t need to create an instance with static attributes; you can use them directly from the class

    • Static properties (methods) start with static

    • Example:

      class Tools{
          static PI = 3.1415926;
          
          static sum(num1: number, num2: number){
              return num1 + num2
          }
      }
      
      console.log(Tools.PI);
      console.log(Tools.sum(123.456));
      Copy the code
  1. inheritance

    • Inheritance is a feature of object orientation

    • Inheritance allows you to introduce properties and methods from other classes into the current class

    • Example:

      (function(){
      
          // Define an Animal class
          class Animal{
              name:string;
              age:number;
              constructor(name:string,age:number){
                  this.name= name;
                  this.age= age;
              }
              sayHello(){
                  console.log('Animals are crying'); }}class Dog extends Animal{
            run(){
                console.log(`The ${this.name}In the run ~ ~ ~ `);
                
            }
            sayHello() {
              console.log('Bow bow bow! '); }}// Define a class representing a cat
        // make Cat inherit from Animal
        class Cat extends Animal{
            sayHello() {
                console.log('Meow, meow, meow! '); }}const dog = new Dog('prosperous wealth'.5);
          const cat = new Cat('Mimi.3);
          console.log(dog);
          dog.sayHello();
          dog.run();
          console.log(cat); cat.sayHello(); }) ()Copy the code
    • Inheritance allows you to extend a class without modifying it

    • rewrite

      • When inheritance occurs, if a method in a subclass replaces a method of the same name in the parent class, this is called method rewriting

      • Example:

        (function(){
            class Animal{
                name:string;
                constructor(name:string){
                    this.name = name;
                }
                sayHello(){
                    console.log("The animals are barking."); }}class Dog extends Animal{
                age:number;
                constructor(name:string,age:number){
                    If you write a constructor in a subclass, you must call the parent constructor in the subclass constructor
                    super(name);
                    this.age= age
                }
                sayHello(){
                    // In the class method, super represents the parent of the current class
                    // super.sayHello(); // The output animal is calling
                    console.log('Bow bow bow! '); // Override the parent method}}const dog = new Dog('prosperous wealth'.3); dog.sayHello(); }) ();Copy the code
      • You can use super in a subclass to complete a reference to the parent class

    • Abstract Class

      • Abstract classes are classes that are designed to be inherited by other classes. They can only be inherited by other classes and cannot be used to create instances

      • The sample

        (function(){
            Abstract classes are not very different from other classes except that they cannot be used to create objects. Abstract classes are designed to be inherited. Abstract methods can be added to abstract classes
        
            abstract class Animal{
                name:string;
                constructor(name:string){
                    this.name = name;
                }
        
                // Define an abstract method
                // Abstract methods: start with abstract, no method body
                Abstract methods can only be defined in abstract classes. Subclasses must override abstract methods
                abstract sayHello():void;
            }
        
            class Dog extends Animal{
                sayHello(){
                    console.log(Woof woof woof); }}class Cat extends Animal{
                sayHello(){
                    console.log(Meow, meow, meow.); }}const dog = new Dog('prosperous wealth');
            dog.sayHello()
        
            const cat  = new Cat("The knife")
            cat.sayHello()
            
        })()
        Copy the code
      • Methods that start with abstract are called abstract methods. Abstract methods have no body and can only be defined in abstract classes. When an abstract class is inherited, the abstract method must be implemented, that is, subclasses must override the abstract method

  2. Polymorphism: a parent class defines a method that does not implement, leaving it to subclasses that inherit from it to implement a different behavior for each subclass

    Note: Using polymorphic bases is an inheritance or interface implementation of a class

    Take, for example, polymorphisms, different forms of a thing. For example, in the code, the variable f is declared to be of Animal type, specifically Dog or Cat. When the object is new, it is known that if it is Dog, then f.at () calls the eat method of the Dog class. If it is Cat, then f.at () calls the eat method of Cat, which is polymorphic!!

6.4 interface

Interfaces function like abstract classes, except that all methods and attributes in an interface have no real values. In other words, all methods in an interface are abstract methods.

An interface is responsible for defining the structure of a class. An interface can restrict the interface of an object. An object can only match the interface if it contains all the attributes and methods defined in the interface.

At the same time, you can have a class that implements an interface that contains all the attributes in the interface.

Example:

(function(){
    // Describe the type of an object
    type myType = {
        name:string.age:number
    };
    The /** * interface is used to define a class structure that defines which properties and methods a class should contain

    interface myInterface{
        name:string;
        age:number;
    }
    interface myInterface{
        gender:string
    }

    const obj:myInterface = {
        name:'sss'.age:11.gender:'male'
    }

    /** * An interface can restrict the structure of a class when defining a class * all attributes in an interface cannot have real values * An interface defines the structure of an object, regardless of real values * all methods in an interface are abstract methods */

    interface myInter{
        name:string;
        sayHello():void
    }

    /** * When you define a class, you can make it implement an interface

    class MyClass implements myInter{
        // There must be name and sayHello methods
        name:string;
        constructor(name:string){
            this.name = name;
        }

        sayHello(){
            console.log("Hello World");
            
        }
        sayHi(){
            console.log("Hello, everyone."); }}const test = new MyClass("peiqi")
    console.log(test.name); test.sayHello(); test.sayHi(); }) ();Copy the code

6.5 Generic

Generics can come into play when defining a function or class in situations where the exact type to be used is uncertain (the types of return values, parameters, and attributes are uncertain).

/** * function fn(a:any):any{ * return a; *} * /

// When defining functions or classes, you can use generics if the type is not clear

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

// You can call functions with generics directly
let result = fn(10);// Generics are not specified

let result2 = fn<string> ("hello"); // Specify generics

// Generics can specify more than one at a time
function fn2<T.K> (a:T,b:K) :T{
    console.log(b);
    return a;
    
}

fn2<number.string> (123."hello"); / / call
console.log(fn2<number.string> (123."hello")); //hello 123

interface Inter{
    length:number;
}

//T extends Inter means that T must make Inter implement a class (subclass)
function fn3<T extends Inter> (a:T) :number{
    return a.length;
}

class MyClass<T>{
    name:T;
    constructor(name:T){
        this.name =name; }}const mc = new MyClass(18)
const mc2 = new MyClass<string> (Sun Wukong)
console.log(mc);
console.log(mc2);
Copy the code

The project of actual combat

snake

The code address

Making the address

reference

Silicon Valley TypeScript Tutorial