This article has participated in the weekend study program, click to see more details

preface

One of the biggest advantages of TypeScript as a superset of JavaScript is static typing, which is simply the ability to determine if the type of variable used is what you expect during compilation.

A language that reports errors when compiled is static, and a language that reports errors when run is dynamic. TypeScript is abbreviated to TS and JavaScript to JS

To use Typescript in a project, of course, it is essential to transform your JS code into TS. The first step in ts is to understand Typescript data types.

Type check mode

Note that the essence of ts type checking is to precompile ts to JS and check whether the data type meets expectations during compilation. No additional data type judgments are added to the compiled JS code.

First, primitive type

With JavaScript basics, learning the following basic types should be straightforward.

  • Boolean Boolean value
  • Number Number type
    • Contains binary, decimal, and hexadecimal numbers
  • String String type
  • void
    • Contains NULL and undpay
    • The default is a subtype of all types, so you can assign a value of void to another type
  • null
  • undefined
  • Symbol (lib must add es6 library files to use)
  • Bigint (lib must add es6 library files to use)

The above eight types are the base of TS, except void, which you should have used in JS. Void contains null and undefined. It is important to note that void, null and undefined are the basic types of TS.

For the symbol and Bigint data types, if you want to use them in TS, you need to add the corresponding auxiliary compilation libraries to the TS configuration file.

// tsconfig.json
{
  "compilerOptions": {
    "lib": [
      "dom"."es5"."scripthost"."es2015.symbol"]}}Copy the code

Basic type definition syntax

const decLiteral: number = 6

// Only null and undefined can be assigned to void
const a: void = undefined
Copy the code

Other types

It can be said that the following types are the focus of TS learning

1. any

The any type means any type, and any type of data passed can be compiled. Values of type any come from dynamic content or user input, and using type any allows them to pass directly through the compile check phase (caution).

2. unknown

  • unknownIs a new type introduced in TS3.0, yesanyType Indicates the security type.
  • whenunknownUntil a type is identified as a type, it cannot be instantiated, getter, function execution, and so on.
let value: unknown = [];

let concat = value.concat([1]);
console.log(concat);

// ERROR Property 'concat' does not exist on type 'unknown'.
Copy the code

As you can see from the above demo, specific instantiation, function execution and other operations cannot be performed on variables that are not of a specific type, even if there is a corresponding method for the result of assignment. To execute the above code correctly, you need to add type protection, as shown below

let value: unknown = [];

if (value instanceof Array) {
    let concat = value.concat([1]);
    console.log(concat);
}

Copy the code

3. never

Represents a type that never exists. It can be a subtype of any type or can be assigned to any type.

  • Never can be assigned to itself
  • Any cannot be assigned to never

The following are common usage scenarios

// A function that throws an exception never returns a value
function error(message: string) :never {
    throw new Error(message);
}

// Empty array, always empty
const empty: never[] = []
Copy the code

An array of 4.

Arrays can be defined in one of two ways, using generics or directly following the element type with a [].

  • Use generic definitions
const list: Array<number> = [1.2.3]
Copy the code
  • Element type followed by []
const list: number[] = [1.2.3]
Copy the code

When declaring an array in TS, you can only define the type of the array element term or the type of any. If you want more granular control over the data type of an array item, you can use the tuple type.

5. A Tuple (a Tuple)

  • You can think of it as an array with a given number and type of elements.
  • The elements contained in a tuple must be of the same type as the declared type, but not more or less, and in the same order.
  • Tuples are subtypes of arrays
let x: [string, number];
x = ['hello'.10]; // OK
x = [10.'hello']; // Error
Copy the code

Tuples cross-border

When inserting a new element of undefined type into a meta-ancestor type, printing the tuple directly will see the newly inserted element, but accessing the corresponding new element directly will report an error.

const tuple: [string.number] = ['a'.1];
tuple.push(2); // ok
console.log(tuple); // [" A ", 1, 2] -> Print normally
console.log(tuple[2]); // Tuple type '[string, number]' of length '2' has no element at index '2'
Copy the code

6. Object

Like object in JS, object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, null, and undefined. This is to define a variable of type Object that can be assigned to ordinary objects, enumerations, arrays, tuples, etc.

7. Enumeration types

Enumeration defines a set of values in which the value of a variable must be included.

(1) Enumeration of numbers

  • When an enumerated type is defined, if no value is assigned, its value is the default array type, accumulating from zero. (when enumerating)
enum Direction {
    Up,
    Down,
    Left,
    Right
}

console.log(Direction.Up === 0); // true
console.log(Direction.Down === 1); // true
console.log(Direction.Left === 2); // true
console.log(Direction.Right === 3); // true
Copy the code
  • After assigning a value to the first value (default 0), subsequent values are accumulated based on the first value
enum Direction {
    Up = 10,
    Down,
    Left,
    Right
}

console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); // 10 11 12 13
Copy the code
  • When one of these items is assigned to another type, the enumeration item default value after that value is invalidated (value error)
enum Direction {
    Up,
    Down,
    Left = 'nice',
    Right
}

let a: Direction = Direction.Down / / 1
let b: Direction = Direction.Right // Enum member must have initializer.
Copy the code

(2) String enumeration

Enumeration of values of type string.

enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

console.log(Direction['Right'], Direction.Up); // Right Up
Copy the code

(3) Heterogeneous enumeration

enum Direction {
    Up = 'Up',
    Down = 23
}
Copy the code
  • This is a mixture of numeric enumeration and string enumeration.
  • Boolean values cannot be used.
console.log(Direction[0]); // Up
Copy the code

(4) Constant enumeration

Enumerations defined with const are constant enumerations. Enumerations can be declared as constants by const, with the advantage that the enumeration object does not exist after compilation.

const enum Direction { Up = 'Up', Down = 'Down', Left = 'Left', Right = 'Right' } const a = Direction.Up; Var a = "Up";Copy the code

If TypeScript must preserve the Direction object, we can add the compilation option –preserveConstEnums

(5) Reverse mapping

A numeric enumeration can find a value by enumeration key, and vice versa. String enumeration can only find a value by key, as shown in the following example:

enum Enum {
    name = 'steven',
    age = 18
}

let a = Enum.age;
let nameOfA = Enum[a];

let b = Enum.name;
let nameOfB = Enum[b];

console.log(a); / / 18
console.log(nameOfA); // age

console.log(b); // steven
console.log(nameOfB); // undefined
Copy the code

Take a look at the compiled result of the above code (js)

var Enum;
(function (Enum) {
    Enum["name"] = "steven";
    Enum[Enum["age"] = 66] = "age";
})(Enum || (Enum = {}));
var a = Enum.age;
var nameOfA = Enum[a];
var b = Enum.name;
var nameOfB = Enum[b];
console.log(a);
console.log(nameOfA);
console.log(b);
console.log(nameOfB);
Copy the code

If you print the value of the Enum in the self-executing function, you can see why the string enumeration cannot find the key from value.

- var Enum;
+ var Enum,o;
    (function (Enum) {
        Enum["name"] = "steven";
        Enum[Enum["age"] = 66] = "age";
+ o = Enum
    })(Enum || (Enum = {}));
    var a = Enum.age;
    var nameOfA = Enum[a];
    var b = Enum.name;
    var nameOfB = Enum[b];
    console.log(a);
    console.log(nameOfA);
    console.log(b);
    console.log(nameOfB);
    
    
+ console.log(o) // { '66': 'age', name: 'steven', age: 66 }

Copy the code

END