This is the first day of my participation in the August More Text challenge

Let’s start with what typeScript is; Officially, it is a super version of javascript with a type system that can be compiled to pure javascript.

1. Type check;

Typescript compiles code with strict static type checking; This way, code reviews are carried out during the coding phase without bringing problems to the line.

2. Language extension;

Es6, asynchronous operation, decorator; Borrow other language features, such as interfaces, abstract classes, and so on.

3. Tool properties;

It can compile to standard javascript and run on any browser, operating system, without any extra runtime overhead.

First, data types

Ts adds void, any, never, meta-ancestor, enumeration, and advanced types on the basis of JS.

As follows:

Boolean, Number, String, Array, Function, Object, Symbol, undefined, null, void, any, never, ancestor, enumeration, advanced type.

First, understand a concept: type annotations.

Function: equivalent to type declarations in strongly typed languages;

Syntax: (variable/function) : type

// Primitive type let bool: Boolean = true; let num: number = 123; let str: string = 'abc'; // STR = 123 // not allowedCopy the code

Assigning STR to 123 (of type number) is not allowed.

There are two ways to declare an array type:

The declaration element is an array of type number:

Let arr1: number[] = [1,2,3]; Let arr2: Array < number | string > = [1, 2, 3, '23'];Copy the code

tuples

let tuple: [number, string] = [0, '1']; tuple.push(2); console.log(tuple); tuple[2]; // You can add elements to primitives, but you cannot access them. Not recommendedCopy the code

function

let add = (x:number,y:number) => x + y;
let compute: (x: number,y: number) => number;
compute = (a,b) => a + b;
Copy the code

object

let obj: {x: number,y: number} = {x: 1, y: 2}; Access object obj.x = 3;Copy the code

symbol

let s1: symbol = Symbol();
let s2: Symbol();
s1 === s2 // false
Copy the code

Undefined, null,

let un: undefined = undefined; let nu: null = null; num = undefined; num = null; // if you set strictNullChecks in tsconfig.json: "strictNullChecks": false, the assignment will succeed.Copy the code

void 

An operator that allows any expression to return undefined; Void 0;

Since undefined is not a reserved word in JS, we even define undefined to override undefined globally; The following code:

(function () { var undefined = 0; Console. log(undefined)})() // 0 Obviously, undefined overwrites undefined globally in this closure.Copy the code

Therefore, void ensures that the function returns undefined.

The value is of any type and can be assigned arbitrarily

Never: indicates that no value will ever be returned.

A function that throws an exception will never return a value.

2. Dead-loop functions

Enumerated type

Users in the Taiwan system often meet to judge the user multiple identity, so the following code you are certainly not unfamiliar.

function initByRole(role){
    if(role ===1 || role === 2){
        // doing
    }else if(role === 3 || role === 4){
        // doing
    }else if(role === 5){
        // doing
    }else{
        // doing
    }
}
Copy the code

Poor readability; It’s hard to remember what numbers mean;

Poor maintainability; Hard coding, pull a launch of the whole body;

At this point, you can use the enumerated types in TS. An enumeration is a set of constants with names. You can associate with the address book in the mobile phone. After the phone number is stored in the name, you only need to find someone to call. There is no need to remember the phone number.

Enumeration types are:

1. Enumeration of numbers;

2, string enumeration;

// Numeric enumeration values start at 0 by default, and subsequent enumerators are incremented. If the initial value is set to 2, the increments start from 2. Enumerations are implemented through the principle of reverse mapping. Enum Role {Reporter=2, // then 3, 4, 5, 6 Developer, Maintainer, Owner, Guest} console.log(role-reporter) // 0 // String enum enum Message {Sucess = 'Congratulations, success! ', Fail = 'Fail! }// String enumeration enum Message {Sucess = 'Success! ', Fail = 'Fail! Enum Answer {N, Y = 'yes'} // const a, b = Char. A, c = 1 + 3, // computed d = math.random (), e = '123'.length} // Const enum Month {Jan, Feb, Mar}let Month = [month.jan, Month.Feb, Month.Mar]; console.log(month); Enum type enum E {a, b}; enum F { a = 0, b = 1}; enum G { a = 'ee2qwca', b = 'bannana' }; let e: E = 3; let f: F = 3; // e === flet e1: E.a = 1; let e2: E.b; // e1 === e2 let e3: E.a = 2; // e1 === e3let g1: G = G.a; let g2: G.a;Copy the code

Interfaces, which constrain the structure and types of functions, objects, and classes, are a code collaboration contract that biubiU abides by and cannot change.

Interface definitions for object types;

Example: Take a set of data and center it on the page.

You can use interface to define the list interface. This interface has two members, ID and name. Let’s define a result that has a member, data, and that member is a List array. Next, define a render function in which result.data is iterated over and the console outputs the ID and name. Assume that result is the data received from the back end and the data format conforms to our definition, as follows:

interface List {
    id: number;
    name:string;
}
interface Result {
    data: List[]
}
function render(result: Result){
    result.data.forEach((value) => {
        console.log(value.id, value.name)
    })
}
let result = {
    data: [
        {id: 1, name:'A', sex: 'male'},
        {id: 2, name: 'B'}
    ]
}
render(result)
Copy the code

In practice, the backend often passes fields that are outside of the convention, and TS is allowed because ts adopts a duck style, a style of dynamic language types. As long as the incoming object meets the interface requirements, it is allowed. But if you use object literals, you get an error

1. Assign an object literal to a variable; As mentioned in the render (result); 2. Type assertion; We're explicitly telling the compiler that our type is Result; render({ data: [ {id: 1, name: 'A', sex: 'male'}, {id: 2, name: 'B'} ] } as Result); Or render (< Result > {data: [{id: 1, name: 'A', sex: 'male'}, {id: 2, name: 'B'}]}); Interface List {readonly ID: number; // Read-only attribute name: string; [x: string]: any; age? : number // Optional attribute}Copy the code

The number of interface attributes above is fixed. When you are not sure how many attributes an interface has, you can use indexable interfaces. Indexable interface that can be indexed by numbers or strings.

Interface for numeric indexing:

interface StringArray {
    [index: number]: string
}
let chars: StringArray = ['A','B'];
Copy the code

Interface for string indexing

interface Names { [x: string]: string; // y:number; [z: number]: string; }Copy the code