05 # Basic type

Insert image description here

type annotation

Function: Equivalent to type declaration in strongly typed language

Syntax: (Variable/Function): type

Primitive type:

let bool: boolean = true;
let num: number = 313;
let str: string = 'kaimo';

Array:

let arr: number[] = [1, 2, 3];
let arr2: Array<number | string> = [1, 2, 3, '4'];

Tuple: It is a special type of array that limits the type and number of array elements.

let tuple: [number, string] = [1, '2'];

Tuple out-of-bounds access,tuple[2] will prompt an error, and this is not recommended for development

tuple.push(2)
console.log(tuple); // [1, '2', 2]
tuple[2]

function

let add = (a: number, b: number) =>  a + b;
// 定义函数类型
let compute: (x: number, y: number) => number;
compute = (a, b) => a + b;

object

// 下面这种事不容许的
let obj: object = {
    
     name: 'kaimo', age: 18 };
obj.age = 313; // 报错 `类型“object”上不存在属性“age”。`
// 需要制定成员类型
let obj1: {
    
     name: string, age: number } = {
    
     name: 'kaimo', age: 18 };
obj1.age = 313; 

Symbol has a unique value

let s1: symbol = Symbol();
let s2 = Symbol();
console.log(s1 === s2);

undefined、null

let u: undefined = undefined;
let n: null = null;

num cannot be assigned to undefined and null, and needs to be enabled tsconfig.json configuration

"strictNullChecks": false

void is a type without any return value

let noReturn = () => {
    
    };

any Any type, no type is specified, you can assign a value to it arbitrarily

let x;
x = 1;
x = [];
x = () => {
    
    };

never will never have a return value type

  • In the function, an error is thrown
  • infinite loop
let error = (msg: string) => {
    
    
    throw new Error(msg)
};
let infiniteLoop = () => {
    
    
    while (true) {
    
    }
}

おすすめ

転載: blog.csdn.net/kaimo313/article/details/134697094