Basic types

All types come after the colon. The core of TS is all about security. Note that TS is compiled into JS with no type, ts is only used during development

1.1 Boolean, number, and string

let bool:boolean = true;
let num:number = 10;
let str:string = 'hello';
Copy the code

“Number” is used to describe types and “number” is used to describe instances.

let num1: number = 1;
let num2: Number = 1; // Classes used to describe instances can also be treated as types
let num3: number = Number(1)
let num4: Number = new Number(1);
Copy the code

1.2 an array

The concept of arrays: a collection of a class of types

let arr1:number[] = [1.2.3];
let arr2:string[] = ['1'.'2'.'3'];
let arr3:(number|string) [] = [1.'2'.3];	 / / and set
let arr4:Array<number | string> = [1.'2'.3]; // the generic way to declare
// If the contents of the array are random, use any
let arr5:any[] = [' '.1{}];Copy the code

1.3 yuan group

To add data to a tuple, you can only add the type stored in the tuple

// Specifies the type of each item in the array
let tuple:[string.number.boolean] = ['hello'.10.true];	// The array must be filled in as required during initialization
// The type defined by the tuple can be put in
tuple.push('world');
tuple[3] = 100;	// Error, cannot change tuple by index
Copy the code

1.4 the enumeration

Enumerations are divided into ordinary enumerations, heterogeneous enumerations and steady on enumerations

enum USER_ROLE {	// Enumeration type uppercase is the norm, not mandatory
    USER, // Starts from 0 by default
    ADMIN,
    MANAGER
}
// {0: "USER", 1: "ADMIN", 2: "MANAGER", USER: 0, ADMIN: 1, MANAGER: 2}
Copy the code

It can be enumerated or inverted

// The compiled result
(function (USER_ROLE) {
    USER_ROLE[USER_ROLE["USER"] = 0] = "USER";
    USER_ROLE[USER_ROLE["ADMIN"] = 1] = "ADMIN";
    USER_ROLE[USER_ROLE["MANAGER"] = 2] = "MANAGER";
})(USER_ROLE || (USER_ROLE = {}));
Copy the code
  • Heterogeneous enumeration

Enumerations can support backlifting, but are limited to indexes that automatically infer from the previous person’s value

enum USER_ROLE {
    USER = 'user',
    ADMIN = 5,
    MANAGER,	// Based on the previous 5, the current is 6
}
Copy the code
  • Constant enumeration

Const does not generate an object (more succinctively), but constant enumerations do not support backlifting

const enum USER_ROLE {
    USER,
    ADMIN,
    MANAGER,
}
console.log(USER_ROLE.USER)// console.log(0 /* USER */);
Copy the code

1.5 nullundefined

Null and undefined are “subtypes of any type”, but strictly (strictNullChecks is true) null can only be assigned to NULL, and undefined can only be assigned to undefined

let u: undefined = undefined;
let n: null = null;
Copy the code

1.6 never

The code never reaches an endpoint, never executes until the end is a “subtype of any type”, such as an error, an infinite loop, a judgment that never gets made

function error(message: string) :never {
    throw new Error("err");
}
function loop() :never {
    while (true) {}}function fn(x:number | string){
    if(typeof x == 'number'){

    }else if(typeof x === 'string'){

    }else{
        console.log(x); // never complete code verification}}Copy the code

1.7 void

Void denotes the return value of a function, and can also describe variables. The value of void can only be null and undefined. Strictly, null cannot be assigned to void

function getVoid() :void {
    return undefined
}
let a:void;
a = undefined;
Copy the code

1.8 any

Type checking is not performed

let arr:any = ['hello'.true, {name:'world'}]
Copy the code

1.9 object

Nonprimitive type

function create(obj: object) {

}
create({});
create(function () { })
create([]);
Copy the code

1.10 SymbolandBigInt

Symbol means unique

const s1: symbol = Symbol('key');
const s2: symbol = Symbol('key');
console.log(s1 == s2); // false
Copy the code

BigInt can accurately calculate numbers beyond the maximum safe number

const num1 = Number.MAX_SAFE_INTEGER + 1;
const num2 = Number.MAX_SAFE_INTEGER + 2;
console.log(num1 == num2)// true


let max: bigint = BigInt(Number.MAX_SAFE_INTEGER)
console.log(max + BigInt(1) === max + BigInt(2))
Copy the code

Type derivation

2.1 Type Derivation

  • The default variable is any if no value is assigned to it

    let name; // The type is any
    name = 'zhufeng'
    name = 10;
    Copy the code
  • When declaring a variable assignment, the assignment type prevails

    let name = 'zhufeng'; // Name is inferred as a string
    name = 10;
    Copy the code

2.2 Packaging Objects

When we use a primitive data type, we call a method on the primitive data type, which by default wraps the primitive data type as an object type

let bool1:boolean = true;
let bool2:boolean = Boolean(1); 
let bool3:Boolean = new Boolean(2);
Copy the code

Boolean is the base datatype, and Boolean is its wrapper class

2.3 Association Type

let numOrStr: string | number;
// The default union type can only call methods that are common to both types without specifying the type
// You can set the corresponding method after the type of the variable is determined
numOrStr = 'abc';
numOrStr = 123;
// If a type is assigned, the method of the corresponding type can be inferred automatically based on the context
Copy the code

2.4 Type Assertion

  • Types of assertions

! Nonnull assertion, which means that something must have a value and must not be null

let name: string | number;
(name! as number).toFixed(2); / / mandatory
((<number>name!) .toFixed(2));
Copy the code

As / <> to force a type to be one of those types, and to force a type to be one of those types

  • Double assertion
let name: string | boolean;
((name! as any) as string);
Copy the code

Try not to use double assertions, which break the type relationship. The assertion is any because any can be assigned to other types

2.5 Literal types

type Direction = 'Up' | 'Down' | 'Left' | 'Right';
let direction:Direction = 'Down';
Copy the code

You can use literals as types and also indicate that only these values can be used (qualified values). Similar to enumeration.