Re-learn TypeScript (1) Basic types

Posted May 27, 20205 min read

Foreword

Everyone knows about the basic situation of TypeScript and the comparison with JavaScript. After all, as of this writing, the latest version of TypeScript has reached 3.9, and it is not new. I've been using it for development for a long time, but I haven't sorted it out from beginning to end before. I just checked and used it when I was coding. Some time ago, because of work needs, I went to read some libraries written by others. Some of the writing methods are very strange. After thinking about it, I still have to start making up classes.

Learn again, starting with the type first. As a superset of JavaScript, it is natural to support JavaScript data types, including Boolean values, numbers and strings, and objects. These are no different from JavaScript and will not be expanded in detail. Here is a brief talk about the types that JavaScript does not support. The more important ones are tuple types and enumerated types.

Tuple

The tuple type allows to represent an array of known quantities and types, the types of the elements need not be the same.

const x:[string, number]= ['hello', 10]

You can think of it as an extension of an array, which is actually a strict array type.

The general array only specifies the element type. But for tuples, when declaring an array, it also specifies the element type at each index in the array. One thing to note here is that for out-of-bounds elements, that is, elements at an index that exceeds the defined length, in versions 2.6 and earlier, the type of out-of-bounds elements will be replaced by a joint type, and access to out-of-bounds elements is not allowed after 2.6.

let x:[string, number]= ['hello', 10]
console.log(x [0].substring(1)) //'ello'
x = [10, 'hello']//error
x [2]= "world"; //error

Enum

The enum type is a supplement to JavaScript's standard data types and declares a set of named constants.

In fact, the essence of the enumerated type is an object in the form of key-value pairs.

//Declaration
enum nums {
    zero,
    one,
    two
}

//compiled js
var nums;

(function(nums) {
nums [nums ["zero"]= 0]= "zero";
nums [nums ["one"]= 1]= "one";
nums [nums ["two"]= 2]= "two";
})(nums ||(nums = {}));

Enumerating members

From the definition of enumeration type, it declares a set of constants, so enumeration members can become enumeration constants, so long as the value is a constant.

Since it is a constant, it is specified that the enumeration members are read-only and cannot be modified and re-assigned.

We can specify enumeration member values in 2 ways

  • Literal

    Specify by numeric literal or string literal

  • Expression or declaration

    Operational expressions or function expressions, declarations, etc. that return calculation results or constants

Basic classification

Enumerations can be divided into different categories according to enumeration members:

  • Number enumeration type

      enum nums {
          zero, //The value of the first member defaults to 0
          one, //1 without initializer value is the value of the previous member +1
          three = 3, //3 use the initializer and specify the initialized constant
          four, //4 without initializer value is the value of the last member +1
          five = nums.zero, //0 can also use the reference of the enumeration member of the enumeration already declared
          six = returnNumber() //6 can use expressions or function calls
        }
    
        function returnNumber() {
          return 6
        }
  • String enumeration type

    One thing to note is that in string enumeration, each member must use a string literal, and calculation values are not allowed.

      enum nums {
        zero = 'ZERO',
        one = 'ONE',
        two = 'TWO',
        three = fn(), //error
        four = four //error
      }
    
      function fn() {
        return 'THREE'
      }
    
      var four = 'F' + 'OUR'

    The enumeration members of the string enumeration need to be initialized. If not initialized, the value of the numeric constant will be added to the member by default. At this time, it is the following heterogeneous enumeration type.

  • Heterogeneous enumeration types

      enum nums {
          zero,
          one = 'ONE',
          two = 'TWO'
      }

_ Digital enumeration generates a reverse mapping table after compilation, that is, in addition to generating a set of key-value pairs, it will also generate a set of value-key pairs. String enumeration does not. Compare the two codes that are actually generated:_

Digital Enumeration Compilation Results

String enum compilation result


According to the enumeration declaration method, it can be divided into the following three types:

  • Common enumeration

    The above examples are ordinary enumerations, so I wo n t expand them in detail.

  • Constant enumeration

    Even if the const modifier is used to emphasize the current enumeration type, constant enumerations are different from regular enumerations, they will be deleted during the compilation phase. In order to avoid the overhead of extra generated code and indirect access to enumeration members, constant enumeration can be used.

    Enumerated members are not allowed to use calculated values, and the enumerated members will be inlined where they are used.

      const enum nums {zero, one, two}
      let numsArr = [nums.zero, nums.one, nums.two]
    
      //The final compiled code:
      //var numsArr = [0/* zero * /, 1/* one * /, 2/* two * /];
  • External enumeration

    Use the declare keyword to declare an enum to describe the shape of an existing enum type.

    External enumeration is similar to type assertion, as long as there is this declaration in development, it means that the current object must exist in the context of the current development environment, you can use the current object at will.

    There is an important difference between external enumerations and non-external enumerations. In normal enumerations, members without an initialization method are treated as constant members. For non-numerous external enumerations, there is no initialization method that is considered to be calculated.

    declare enum nums {zero = 0, one, two}

  • External constant enumeration

    Enumerated types declared jointly using the declare and const keywords are not much different from constant enumerations.

    declare const enum nums {zero, one, two}

Any

any can be used to represent any type, usually used for variables whose type is unclear at the development stage, such as user input or third-party code libraries, or when the original js code is changed to ts. It is recommended to use less unnecessary cases, after all, one of the advantages of TypeScript is strong typing.

const x:any = 'TypeScript'
const y:number = 12
const z:any = true

Void, Null and Undefined

The void type is like the opposite of the any type, it means that there is no type. Variable values can only be undefined and null.

For the two types undefined and null, their values are undefined and null. By default, they are subtypes of all types(except the never type below), which can be assigned to Other types of variables; but if strict null checking is enabled in the compilation configuration(--strictNullChecks:true), null and undefined can only be assigned to any and each of them(with one exception undefined can be assigned to void).

function fn(msg:string):void {
  console.log(msg)
}

const x:any = null
const y:number = undefined //strict null check will report an error

Never

The never type represents the type of values that never exist. It is a subtype of any type and can be assigned to any type; however, the NO type is a subtype of never or can be assigned to the never type(except for never itself). Even any cannot be assigned to never.

//The function returning never must have an unreachable end point
function error(message:string):never {
  throw new Error(message);
}
function infiniteLoop():never {
  while(true) {
  }
}

const x:never = null //error
const y:never = undefined //error

Reference

TypeScript official website

typescript enumeration

One article gives you a thorough grasp of TS enumeration