Introduction to typescript

Typescript is a superset of JavaScript. If you’re familiar with JavaScript, you know that JavaScript is a weakly typed language. For example, if you declare a variable, you can assign any type of value to that variable. Focus on its type above, it can be said that it is an upgraded version of JS, make up for the shortcomings of JS

Typescript environment setup

  1. Download and install Node

    Official website: nodejs.org/zh-cn/downl… (Install 64-bit or 32-bit depending on your computer configuration)

    Check whether the installation is successful: Open the cli anywhere and enter node -v to see the version number

  2. Install typescript globally using NPM

    Type NPM i-g typescript in a command line window

    Check whether the installation is successful: command line input TSC if a long pile of things out, the installation is successful

  3. Create a TS file

  4. Ts files are compiled using TSC

    • The CLI is displayed
    • In the directory where the TS file resides
    • Run the TSC xxx.ts command
    • A JS file appears in the same location indicating successful compilation

With that done, you can write your own TS project


Basic types of

  • Type declaration

    • Type declarations are a very important feature of TS

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

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

    • In short, a type declaration sets the type of a variable so that it can only store the value of one of the types

    • Grammar:

      letVariable: TypeletVariable: Type = valuefunction fn(Parameter: type, parameter: typeType) :{... }Copy the code
  • Type Usage Examples

    let a: number
    a = 20 // There is no error in this line
    a = 'Hello' // Can't assign type "string" to type "number".
    
    let b: string
    b = 'Hello' // There is no error in this line
    b = 123 // Can't assign type "number" to type "string".
    
    let c: boolean
    c = true // There is no error in this line
    c = 14 // Can't assign type 'number' to type 'Boolean'.
    c = 'Hello' // Cannot assign type "string" to type "Boolean".
    
    function sum(a: number, b: number) :number {
      return a + b
    }
    console.log(sum(10.20)) / / 30
    // This is a function that sums up two numbers. In js, we do not declare the type of the argument, we can pass in any type of value, and only the number is passed in will do the addition operation, if there is a non-number string concatenation, we can declare the type of the argument, and we can declare the type of the return value, as shown in the parentheses: Number 'is a type declaration of the return value of a function
    
    sum(10.'hello') // The second argument will report an error, the number is declared, cannot pass string
    
    let obj: {name: string, age? : number}// Attribute name followed by? Sign, indicating that the property is optional and can be given or not given
    obj = {name: 'zs'.age: 12} // No error will be reported
    // obj = {name: 'zs'
    
     // The object type, name is a mandatory value, can be passed any key value pair, or not
    let y: { name: string, [propName: string]: any }
    y = { name: 'as'.age: 23 }
    
    / / function
    let p: (a: number, b: number) = > number
    
    p = function (a, b) :number {
      return a+b
    }
    p(10.23)
    
    
    / / array
    // let h: number[]
    let h: Array<number>
    h = [123.23.343434]
    
    let m: string[]
    m = ['23'.'45']
    // tuple. Tuples are arrays of fixed length
    let j: [number, string]
    j = [23.'23']
    
    / / enum enumeration
    enum Gender{
      Male = 0,
      Female = 1
    }
    let i: { name: string, gender: Gender }
    i = {
      name: 'zs'.gender: Gender.Male
    }
    console.log(i.gender === Gender.Male)
    
    / / &
    let x: {name: string} & {age: number}
    x = { name: 'ls'.age: 23 }
    
    / / alias
    type myType = {
      name: string,
      age: number
    }
    
    let bb: myType = {
      name: 'zs'.age: 15
    }
    Copy the code

    A warning appears on the last line of the code above, which is that when TS specifies a type, this can copy the value of that type, not any other type

  • Automatic judgment type

    • 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 if your variable is declared and assigned at the same time, you can omit the type declaration

      let d = 10 // ts adds type number to variable d
      d = 'Hello' // Can't assign type "string" to type "number". let d: number
      
      let e = true // let e: boolean
      let f = 'Hello' // let f: string
      // Same as above
      Copy the code
  • type

    type example describe
    number One, five, 98 Any Numbers
    string ‘123’, ‘helli’ Arbitrary string
    boolean true, false Boolean value true or false
    literal itself The value of the constraint variable is the value of the literal
    any * Any type (like JS)
    unknown * Type safe any
    void A null value (undefined) No value (or undefined)
    never There is no value It can’t be any value
    object {name: ‘zhang SAN ‘} 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, TS new type
    / / any type
    let a: any
    a = 2
    a = true
    a = 'hello'
    // Can be any value
    
    / / unknown type
    let b: unknown
    b = 2
    b = true
    b = 'hello'
    // This is the same as any
    
    // The difference between the two
    let c: string = 'Hello'
    c = a // The type of a of any type will assimilate c, and the type of C will become unclear
    
    c = b // Can't assign type "unknown" to type "string".
    // Resolve the error
      / / 1.
      if(typeof b === 'string') {
          c = b // No error is reported
      }
      / / 2.
      c = b as string
      / / 3.
      c = <string>b
    Copy the code
  • rename

    Use type to rename a type

    type myType = {
        name: string,
        age: number
    }
    
    const obj: myType = {
        name: 'zs'.age: 13
    }
    Copy the code

Compiler options

  • Auto-compile file

    • When compiling a file, using the -w command, the TS compiler automatically monitors the file for changes and recompiles the file if it changes

    • Example:

      tsc xxx.ts -w
      Copy the code
  • Automatically compile the entire project

    • If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files

    • However, to use the TSC command directly, you must first create a TS configuration file tsconfig.json in the project root directory

    • Tsconfig. json is a JSON file. After adding the configuration file, you only need TSC to compile the entire project

    • Configuration options:

      • include

        • Defines the directory where you want the files to be compiled
        • Default value:"* * / *"
        • Example:
          • "include": ["src/**/*", "tests/**/*"]
          • In the example above, all files in the SRC directory and tests directory are compiled
      • exclude

        • Define the directories that need to be excluded
        • Default value:["node_modules", "bower_components", "jspm_packages"]
        • Example:
          • "exclude": ["./src/hello/**/*"]
          • In the example above, the file search in the hello directory under SRC is not compiled
      • extends

        • Define inherited configuration files
        • Example:
          • "extends": "./configs/base"
          • In the previous example, the current configuration file automatically contains all the configuration information in the base.json directory in the config directory
      • files

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

        • Example:

          "files": [
              "core.ts"."sys.ts"."types.ts"."scanner.ts"."parser.ts"."utilities.ts"."binder.ts"."checker.ts"."tsc.ts"
          ]
          Copy the code
      • compilerOptions

        • Compiler options

        • Example:

          "compilerOptions": {
              "target": "ES3".// target specifies the version of ES to which TS is compiled
              "module": "es2015".// module specifies the specification of the modularity to use
              "lib": ["dom"].// lib is used to specify the library to be used in the project
              "outDir": "./dist".// outDir specifies the directory where the compiled file resides
              "outFile": "./dist/app.js".// Merge the code into one file
                  // When outFile is set, all global scope code is merged into one file
              "allowJs": false.// Whether to compile JS files. The default is false
              "checkJs": false.// Check whether the JS code is syntactically correct. The default is false
              "removeComments": false.// Whether to remove comments
              "noEmit": false.// No compiled files are generated
              "noEmitOnError": true.// The compiled file is not generated when there are errors
              "alwaysStrict": true.// Set strict mode for compiled files. Default is false. There is no setting when modularity is introduced
              "noImplicitAny": true.// Whether implicit any is not allowed
              "noImplicitThis": false.// Untyped this is not allowed. Default is false
              "strictNullChecks": false.// Check strictly for null values
              "strict": false.// All strictly checked master switches
          }
          Copy the code

webpack

  • Install webpack

    npm i webpack webpack-cli ts-loader -D
    Copy the code

    You don’t need to download typescript if you already have it in your project; if not, download and install it yourself

  • You can see the installed tools in the package.json file. If package.json is not present in the project, you can initialize the project NPM init and see that a package.json file has been created

  • Create webpack.config.js in the project root directory

  • Configure it in a file

    const path = require('path')
    
    module.exports = {
        // Specify the entry file
        entry: './src/xxx.ts'.// Specify the directory where the package file resides
        output: {
            // Specify the directory to pack the files
            path: path.resolve(__dirname, 'dist'),
            // The name of the packaged file
            filename: 'bundle.js'.// Tells WebPack to pack the generated file without using the arrow function to call itself
            environment: {
                arrowFunction: fasle
            }
        },
        
        // Specify modules to use when webPack is packaged
        module: {
            // Yes loader rule
           rules: [{// test specifies the file in which the rule takes effect
                   test: /\.ts$/.// The loader to use
                   use: 'ts-loader'.// Files to be excluded
                   exclude: /node-modules/}}}]Copy the code

    This is the most basic webPack configuration file

    To use webpack, configure “build”: “webpack” under scripts in package.json.

    At this point, we have to write an HTML page by hand each time and then introduce the packed JS file into it and open it with the browser, which is very inconvenient, so we need another plug-in htML-webpack-plugin

    Package automatically generates index.html

    download

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

    use

    • Used in the webpack.config.js file

      const HtmlWebpackPlugin = require('html-webpack-plugin')
      const htmlPlugin = new HtmlWebpackPlugin({
          template: './src/index.html'.filename: './index.html'
      })
      module.exports = {
          / /... Omit the other
          // Configure the WebPack plug-in
          plugins: [htmlPlugin]
      }
      Copy the code

    Automatic packaging

    • So far, the basic configuration is complete, but there is a problem that each project is packaged manually, so another plugin, Webpack-dev-server, will start a webPack built-in server, and each project will be packaged automatically

    • The installation

      npm i webpack-dev-server -D
      Copy the code
    • Configure “start” under scripts in package.json: “webpack serve –open chrome.exe”

    Setting reference modules

    • Configure it in the webpack.config.js file

      module.exports = {
          / /... Omit the other
          // Set the reference module
          resolve: {
              extensions: ['.ts'.'.js']}}Copy the code

    Package file compatibility

    • Resolve compatibility issues with Babel

    • The installation

      npm i -D @babel/core @babel/preset-env babel-loader core-js
      Copy the code
    • Need to be configured in webpack.config.js

      module.exports = {
           // Specify modules to use when webPack is packaged
          module: {
              // Yes loader rule
             rules: [{// test specifies the file in which the rule takes effect
                     test: /\.ts$/.// The loader to use
                     use: [
                         / / configuration Babel
                         {
                            // Specify the loader
                           loader: 'babel-loader'./ / set the Babel
                           options: {
                               // Set the predefined environment
                               presets: [[// Specify the environment plug-in
                                       "@babel/preset-env".// Configuration information
                                       {
                                           // Be compatible with the target browser
                                           targets: {
                                               "chrome": "88"
                                           },
                                           // Specify the corejs version
                                           "corejs": "3".// Corejs "usage" indicates loading on demand
                                           "useBuiltIns": "usage"}]]}},'ts-loader'].// Files to be excluded
                     exclude: /node-modules/}}}]Copy the code

    An abstract class

    • A class that is specifically used for inheritance
    • useextendsTo inherit
    // Abstract class Classes that begin with abstract
    // An abstract class cannot create an instance, but can only be inherited
    // Abstract classes are classes designed for inheritance
    // Abstract methods can be added to abstract classes
    abstract class Person {
        name: string
        constructor() {
            this.name = name
        }
        // Abstract methods
        abstract sayHello(): void
    }
    / / inheritance
    class China extends Person {
        If sayHello is not defined internally, an error will be reported
        sayHello() {
            console.log("Hello")}}const china = new China("zs")
    Copy the code

    interface

    • The alias type can be used to rename a type. It can be used to rename a type when there are many types. It is more convenient to use

    • The interface can be repeatedly declared, but the alias cannot be repeatedly declared. The interface repeatedly declared must contain all the attributes or methods of the interface with the same name. Otherwise, an error occurs

    • To use through implements

      interface myInterface {
          name: string
          sayHello(): void
      }
      interface myInterface {
          age: number
      }
          // implements the interface
      class Obj implements myInterface {
          // If an attribute or method is missing, an error will be reported. The attribute is declared and initialized
          name: string
          age: number
          constructor(name: string, age: number) {
              this.name = name
              this.age = age
          }
          sayHello() {
              console.log('Hello')}}Copy the code

    Encapsulation of attributes

    • Public modifies public properties that can be modified outside the class

    • Private modifies private attributes that can only be modified within a class

    • Protected properties that can only be used within the current class or a subclass of the current class. Instance objects of the class cannot be accessed

      class Person {
          private name: string
          private age: number
          
          constructor(name: string, age: number) {
              this.name = name
              this.age = age
          }
          // The property is not accessible externally because the private modifier was added to the front of the property.
          // Can provide methods to expose attributes
          get name() {
              return this.name
          }
          set name(value: string) {
              // Add some restrictions to this to prevent malicious changes
              // The initiative is in the hands of the creator, not the user
              this.name = value
          }
      }
      
      const per = new Person(name: 'zs'.age: 22)
      
      // This line of code will report an error if a property in a class has a private modifier and does not expose setter methods.
      // The set name() exposed inside can change the property, then no error
      per.name = 'ls' 
      
      console.log(per)
      
      // Now the properties are set directly in the object and can be changed arbitrarily
      // Attributes can be arbitrarily modified, which makes the data in the object very insecure
      // Prevent malicious changes so modifiers can be used
      Copy the code

      Grammar sugar writing

      class A {
          name: string
          age: number
          constructor(name: string, age: number) {
              this.name = name
              this.age = age
          }
      }
      / / is equivalent to
      class A {
          constructor(public name: string, public age: number){}}Copy the code

    The generic

    • When defining functions or classes, you can use generics if the type is unclear

      function fn<T> (a: T) :T {
          return a
      }
      
      / / usage
      // Can be called directly
      fn(10) // Do not specify a generic type, TS can automatically determine the type
      fn<string>('hello') // Specify generics
      
      // Specify multiple generics at the same time
      function fn1<T.X> (a: T, b: X) :T {
          console.log(b)
          return a
      }
      fn1(123.'hello')
      fn1<number, string>(123.'hello')
      
      // Generics with scope
      interface Inter {
          length: number
      }
      function fn2<T extends Inter> (a: T) :number {
          return a.length
      }
      
      // Classes can also use generics
      class App<T> {
          name: T
          constructor(name: T) {
              this.name = name
          }
      }
      const app = new App('zs') // Generics are not specified
      // const app = new app 
                
                 ('zs') // Specify generics
                
      Copy the code