This is the 23rd day of my participation in the August More Text Challenge.More challenges in August


TS Basic Type

(1) Boolean, number, string, Null

  • Add type annotations after the variable name

    • Type annotation: A lightweight way to add constraints to a function or variable
    • TypeScriptProvides static code analysis, which can analyze code structure and provide type annotations
    / / a Boolean
    let isDone: boolean = true
    
    / / digital
    let num: number = 10
    
    / / string
    let str: string = 'Ruovan'
    
    / / null, and undefined
    let n: null = null
    let u: undefined = undefined
    
    Copy the code

    By default, null and undefined are subtypes of all types, meaning they can be assigned to any type

    But other types cannot be assigned to each other, e.g

    let num: number = 10
    
    num = '10' // can't assign type 'string' to type 'number'
    
    Copy the code

(2) Array

  • Arrays can be defined in two ways:

    • First: append the element type with []

      / / followed by []
      let arr: numer[] = [1.2.3]
      
      Copy the code
    • Second: Use Array generics Array< element type >

      // Array generics
      let arr: Array<number> = [1.2.3]
      
      Copy the code
  • Array type

    • The element type can be separated by |, says can be a variety of types

      // Multiple types
      let arr: (number | string) [] = [1.'2'.3]
      
      Copy the code
    • Element types can be wrapped with {} to represent an array of object types

      Note: It is already clear what properties are inside the object. And properties of what type, can’t be other properties or other types

      let arr: {name: string.age: number}[] = [
          { name: 'ruovan'.age: 24 },
          { name: 'composition'.age: 18}]Copy the code

(3) tuples

  • Arrays are usually composed of values of the same type, but sometimes we need to store different types of values in a single variable, so we can use tuples

    • The tuple type allows you to represent an array with a known number and type of elements
    • Of the elements of a tupleTypes don't have to be the same
    • When a tuple is assigned, the value of each attribute must be supplied
    • Tuples are used in the same way as arrays
    // Define a tuple named tuple
    let tuple: [string.number]
    
    // Initialize tuples in the correct type order
    tuple = ['tuple'.123]
    
    Copy the code

(4) Enumeration

  • Enumeration: can be used to define someConstants with names.
    • Application: use some value to represent some state, use enumeration to define some constants with names, easy to understand
(a) Enumeration of numbers
  • By default, all members of a numeric enumeration are of type Number. By default, elements are numbered starting at 0, followed by ascending elements

    • Digital enumerations also support reverse mapping, that is, they can be derived from enumerations to enumeration names
    // Define an enumeration type
    enum Demo {
        A,
        B    
    }
    
    Demo.A / / 0
    Demo.B / / 1
    
    // Can be mapped backwards
    Demo[0] // 'A'
    Demo[1] // 'B'
    
    / / the compiled
    "use strict"
    var Demo;
    (function (Demo) {
      Demo[(Demo["A"] = 0)] = "A"
      Demo[(Demo["B"] = 1)] = "B"
    })(Demo || (Demo = {}))
    
    Copy the code
  • You can also specify the value of a member manually. If a member is set to a value, the values are incremented

    • Of course, it is possible to assign all values manually, so that there is no incrementing feature
    enum Demo {
        A = 2,
        B     
    }
    
    Demo.A // log: 2
    Demo.B // log: 3
    
    Demo[2] // log: 'A'
    Demo[3] // log: 'B'
    
    Copy the code
(b) String enumeration
  • All members of the String enumeration are strings and must be assigned when initialized

    • There is no auto-increment feature in string enumeration, no reverse mapping feature
    enum Test {
        A = 'a',
        B = 'b'
    }
    
    Test.A // log: 'a'
    Test.B // log: 'b'
    
    Test['a'] // Error, no reverse mapping
    
    / / the compiled
    "use strict"
    var Test
    (function (Test) {
        Test["A"] = "aaa"
        Test["B"] = "bbb"
    })(Test || (Test = {}))
    
    Copy the code
(c) Heterogeneous enumeration
  • Heterogeneous enumerations are equivalent to a combination of numeric enumerations and string enumerations, but are rarely used

    enum Demo{ 
        A = 1,
        B = 'b'
    }
    
    Copy the code
(d) Constant enumeration
  • Constant enumerations are prefixed with the const keyword

    • It does not generate any for enumeration type compilationJavascriptInstead, use the member’s value directly
    • Reverse mapping is not supported
    const enum Direction {
      NORTH,
      SOUTH,
      EAST,
      WEST,
    }
    
    let dir: Direction = Direction.NORTH
    
    / / the compiled
    "use strict"
    var dir = 0 /* NORTH */
    
    Copy the code

(5) Any

  • The any type can represent any type, which makes any a TypeScript top-level type (also known as a global super type)

    • It can be assigned to any type, or even to any method
    • You can useanyType to mark variables whose type is not known at programming time
    • Can beanyType to perform any operation without performing any kind of checking beforehand
    / / any type
    let notSure: any = 10
    notSure = '10'
    notSure = true
    
    Copy the code

(6) Unknown

  • An unknown type represents an unknown type and is another top-level type

    • It can be assigned to any type, but cannot be used by any method, because it is unknown
    • unknownA type can only be assigned toanyThe type andunknownType itself
    / / unknown type
    let value: unknown
    value = true
    value = 42
    
    // Cannot be assigned to any other type
    let value1: number = value // Error
    let value2: string = value // Error
    
    / / can only be assigned to any | unknown
    let value3: any = value
    let value4: unknown = value
    
    Copy the code

(7) Void

  • The void type means that there is no type — an empty type

    • In general, when a function returns no value, its return value type isvoid
    • When declaring a function return value type, add a type annotation after the method name
    / / function: it means the function return value is null (null | | undefined)
    function func1() :void {
        console.log('-- -- -- -- -- -- --)}Copy the code
    • Declare avoidA variable of type is useless because it can only benullorundefined
    // Void type void
    let unusable1: void = null
    let unusable2: void = undefined
    
    Copy the code

(8) Never

  • The never type represents the type of a value that never exists

    • For example,neverTypes are those that always willAn exception is thrownOr at allThere will be no return value, orArrow function expressionThe return value type of
  • useneverYou can avoid the possibility that a new union type has no corresponding implementation, and the goal is to write type-safe code

    // A function that returns never must have an unreachable end
    function error(message: string) :never {
      throw new Error(message)
    }
    
    function infiniteLoop() :never {
      while (true) {}}Copy the code

I front-end side dish chicken, if there is wrong, please forgive