TypeScript tuple type enumeration type

tuple type

A tuple is a combination of a fixed number of elements of different types.
A tuple differs from a set in that the elements in a tuple can be of different types and there is a fixed number of them. The nice thing about tuples is that you can pass multiple elements as a unit. If a method needs to return multiple values, these multiple values ​​can be returned as a tuple without creating an additional class to represent it.

let list:[number,string] = [1,'zs']

let list1: readonly [number,boolean,string,undefined] = [1,true,'zs',undefined]

When assigning or accessing an element with a known index, the correct type is obtained:

let arr:[number,string] = [1,'zs']
arr[0].length //错误
arr[1].length //正确
//数字是没有length 的

out of bounds element

let arr:[number,string] = [1,'zs']
 
arr.push(true) //错误

enumerated type

Define our enums using the enum keyword

1. Numeric enumeration

For example, define the color: red, green, blue Red = 0 Green = 1 Blue= 2 represents red 0, green is 1, and blue is 2

// 第一种方式
enum Types{
    
    
   Red,
   Green,
   BLue
}

// 第二种方式  ts定义的枚举中的每一个组员默认都是从0开始的

enum Types{
    
    
   Red = 0,
   Green = 1,
   BLue = 2
}
//默认就是从0开始的 可以不写值

growth enumeration

We define a numeric enum, initialized to 1 using Red. The remaining members will automatically grow from 1. In other words, Type.Red has a value of 1, Green is 2, and Blue is 3

enum Types{
    
    
   Red = 1,
   Green, // 2
   BLue // 3
}

2. String enumeration

In a string enum, each member must be initialized with a string literal, or with another string enum member.

enum Types{
    
    
   Red = 'red',
   Green = 'green',
   BLue = 'blue'
}

3. Heterogeneous enumeration

Enums can mix string and numeric members

enum Types{
    
    
   No = "No",
   Yes = 1,
}

4. Interface enumeration

Define an enumeration Types Define an interface A He has a property red value Types.a

   enum Types {
    
    
      a,
      b
   }
   interface A {
    
    
      red:Types.a
   }
 
   let obj:A = {
    
    
      red:Types.a
   }

5. const enumeration

Both let and var are not allowed declarations can only use const

const enum Types{
    
    
   No = "No",
   Yes = 1,
}

Guess you like

Origin blog.csdn.net/qq_52099965/article/details/128082993