typescript new type

New types: tuple, enumeration, never, void, any

(1) Tuple

A tuple is an array that specifies the [number of elements] and [each element type]

let arr:[number, string, boolean] = [1, 'hah', true]

There must be a one-to-one correspondence, and there can be no moths, such as adding an array, etc.

let arr1:[number, string, boolean] = [1, 'hah', true, 'dd']

The above code reports an error

Features of tuples: (1) To specify the number of elements (2) To specify the type for each element

(2) Enumeration

enum 枚举名 {
  枚举1 = 枚举值1,
  枚举项2 = 枚举值2,
  ...
}

example:

enum info {
  sex = '女',
  age = 12,
}

Enumeration can also not specify the enumeration value, at this time the default value is assigned from 0

enum info {
  sex,
  age,
  name
}

console.log(info)

Equivalent to 

{ sex: 0, age: 1, name: 2 }

Use in business:

enum sex {
  boy = 1,
  girl = 2,
  unknown = 3
}

let userSex: sex = sex.boy
console.log(userSex) // 1

if (userSex == sex.boy) {
  console.log('男孩')
} else {
  console.log('未命中')
}
// 输出男孩

Automatically detect when I make a judgment

(Three) void: generally used for functions with no return value

(4) Never: represents the type of non-existent value, and is often used for the return value type of the function of [throwing error] or [infinite loop]

Note: the never type is the bottom type in ts, and all types are the parent types of the never type

(5) any: any type

 

 

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/108699291