The last section covered the syntax for type declarations, and we went on to learn more about variable types

  • Literal types, for example

    let a: "male" | "female" // The type of a can only be male or female, i.e
    a = "male" / / right
    a = "female" / / right
    a = "hello" // Error, a cannot be a value other than male or female
    Copy the code
  • Any: indicates any type, for example

    // Explicitly declare variables of type any (not recommended)
    let a: any;
    a = "hello" / / right
    a = 1 / / right
    a = true / / right
    
    // Implicitly declare variables of type any (not recommended)
    let b;
    b = 1
    b = "hello"
    b = true
    Copy the code

    Declare a variable to be of type any. You can assign any type of value to a variable. Declaring a variable to be of type any disables the compiler’s checking of the type of the variable, as in JavaScript. When using TS, it is not recommended to declare variables of type any.

  • Unknown type: indicates the unknown type. Type safety any, for example

    let a: any
    a = 1
    a = "hello"
    a = true
    
    let b: unknown
    b = 1
    b = "hello"
    b = true
    
    let s: string
    s = a / / right
    s = b / / error
    Copy the code

    The difference between the unknown type and the any type

    Similarities: Variables declared as type unknown and variables declared as type any can be assigned to any type of value

    Difference: Variables of type any can be assigned to variables of any type

    Variables of unknown type cannot be assigned to variables of other types

    When we assign s to a variable that was originally a string, we assign s to a variable that is a Boolean. The any type not only causes problems for us, but also for others. So declaring variables of type any is strongly discouraged. If you need to assign an unknown variable to a variable of another type, you can do so

    // The first type, if judgment
    if(type b === "string") {
    	s = b
    }
    
    // The second, type assertion, is used in two ways
    s = b as string
    s = <string>b
    Copy the code
  • Void: indicates that the return value is null, for example

    function fn() :void {
      console.log("Return value is null")}// return undefined
    function fn() :void {
      return undefined
    }
    Copy the code
  • Never indicates that a result is never returned, and undefined cannot be returned