Summary of TypeScript knowledge points

1. What is TypeScript?

  • TypeScript is a language built on top of JavaScript
  • A superset of Javascript
  • Can be executed on any platform that supports JavaScript
  • TypeScript extends JavaScript and adds types
  • TS cannot be directly executed by a JS parser, it needs to be compiled into JS

2. What does TypeScript add?

  • type
  • Support new features of ES
  • Add new features that ES does not have
  • Rich configuration options
  • powerful development tools

3. Build the development environment

  1. Download and install Node.js (omitted)
  2. Use npm to install typescript globally (enter the command line and enter: npm i -g typescript, to see if the installation is successful)
  3. Create a ts file
  4. Use tsc to compile the ts file (execute command: tsc xxx.ts)

4. Basic types

  • type declaration
    也可以 直接使用字面量进行类型声明

    let q:10;
    q = 10;
    

    可以使用 | 来连接多个类型(联合类型)

    let b: 'male' | 'female';
    b = 'male';
    b = 'female';
    
  • automatic type judgment

type:

  1. boolean

  2. number

  3. string

  4. Array array(There are two ways to define an array. The first one can be followed by [ ] after the element type, indicating an array composed of elements of this type, and the second way is to use array generics, Array<element type> )
    insert image description here
    insert image description here

  5. Tuples Tuple(that is, fixed-length arrays)

  6. enumerateenum

  7. Any(Indicates any type. Setting a variable type to any is equivalent to turning off TS type detection for the variable. It is not recommended to use the any type.) If the declared variable does not specify a type, the TS parser will automatically determine the type of the variable is any (implicit any)

  8. unknown(type-safe any)

  9. Void(Used to indicate empty, taking a function as an example, it means a function with no return value)

    function fn():void{
          
          
      return undefined;
    }
    
  10. Null 和 Undefined

  11. Never(indicating that a result will never be returned)

  12. Object

     //{
          
          }用来指定对象中可以包含哪些属性
     //语法: {
          
          属性名:属性值,属性名:属性值}
     //在属性名后边加上?,表示属性是可选的
     let ad: {
          
          age?: number, name: string}
     let dc: object;
     dc = {
          
          };
     
     //[propName: string]:any 表示任意类型的属性
     let cc: {
          
          name: string, [propName: string]:any};
     cc = {
          
          name: '猪八戒', age: 18, gender: '男'}
     
     //设置函数结构的类型声明
     //语法:(形参:类型,形参:类型) => 返回值
     let ar: (a: number, b: number) => number;
     ar = function(n1, n2): number {
          
          
       return n1 + n2;
     }
    
  13. 类型断言 as 或者 <>(can be used to tell the parser the actual type of the variable)

  14. 类型的别名
    insert image description here

5. Compile options

  1. Automatically compile a single filetsc ts文件名 -w

  2. All files are automatically compiled, you need to add a tsconfig.json file, and then input tsccan compile all js files, and input tsc -wcan monitor all ts files

  3. The tsconfig.json file is the configuration file of the ts compiler, and the ts compiler can compile the code according to its information

  4. include is used to specify which ts files need to be compiled

    //**表示任意目录 * 表示任意文件
     "include": [
       "./src/**/*"
     ]
    //exlude表示不需要被编译的文件目录
     "exlude": [
     "./src/hello/**/*"
     ]
    
  5. compilerOptions compiler options

6. Use webpack to package ts code

  1. npm init -yProject initialization pakage.jsonmakefile

  2. Install four dependenciesnpm i -D webpack webpack-cli typescript ts-loader

  3. Add in the generated package.json file
    insert image description here

  4. Create tsconfig.json file

    {
          
          
     "compilerOptions": {
          
          
       "module": "ES2015",
       "target": "ES2015",
       "strict": true
     }
    }
    
  5. Create webpack.config.js file

    //引入一个包
    const path = require('path');
    
    module.exports = {
          
          
      //指定入口文件
      entry: "./src/index.ts",
    
      //指定打包文件所在目录
      output: {
          
          
        //指定打包文件的目录
        path: path.resolve(__dirname, 'dist'),
        //打包后文件的文件
        filename: "bundle.js"
      },
    
      //指定webpack打包时要使用模块
      module: {
          
          
        //指定要加载的规则
        rules: [
          {
          
          
            //test指定的规则生效的文件
            test: /\.ts$/,
            //要使用的loader
            use: 'ts-loader',
            //要排除的文件
            exclude: /node-modules/
          }
        ]
      }
    }
    
  6. Execute npm run buildto package

  7. Install babel to solve compatibility issuespm i -D @babel/preset-env babel-loader core-js

7. Object Oriented

  1. kind

    //使用class关键字来定义一个类
    /**
     * 对象中主要包含了两个部分:
     * 属性
     * 方法
     */
    class Person {
          
          
      //定义实例属性
      name: string = '孙悟空';
      //在属性前使用static关键字可以定义类属性(静态属性)
      static age: number = 18;
    	}
    	
    const pre = new Person();
    console.log(pre);
    console.log(pre.name, Person.age);
    

    ![Insert picture description here](https://img-blog.csdnimg.cn/e817d725558c4fcb851c5b7d49f95c8b.png

  2. Constructor and this (this in the ts instance method is the object calling the method)

    class Dog{
          
          
      name: string;
      age: number;
    
      //constructor被称为构造函数
      //构造函数会在对象创建时调用
      constructor(name: string, age: number) {
          
          
        //在实例方法中,this就表示当前的实例
        //在构造函数中当前对象就是当前新建的那个对象
        //可以通过this向新建的对象中添加属性
        this.name = name;
        this.age = age;
      }
    
      bark() {
          
          
        // alert('wangwang')
        //在方法中可以通过this来表示当前调用方法的对象
        console.log(this);
        
      }
    }
    
    const dog = new Dog('小黑', 5);
    const dog2 = new Dog('小白', 15);
    
    // console.log(dog);
    // console.log(dog2);
    
    dog2.bark(); //this就是'小黑'
    
    

Guess you like

Origin blog.csdn.net/weixin_46319117/article/details/118930397