ts的常见复杂类型

ts常见复杂类型有object、数组、元组、枚举、普通对象

1、object非原始类型
点击查看代码
enum Direction {
   Center = 1
}

let value: object

value = Direction //枚举类型
value = [1] //数组
value = [1, 'hello'] //元组
value = {} //普通对象

注意:除number,string,boolean,symbol,null 或 undefined 之外的类型,
像数组、元组、枚举、普通对象均属于object类型

2、数组
数组的创建的两种方式:

广泛使用:
let arr1:number[] = [1, 2, 3];
泛型:
let arr2:Array<number> = [1, 2, 3];
注意:数组内的元素是纯元素,像纯数字、纯字符串这样的的纯数组

3、元组
点击查看代码
//元组允许的元素类型
let moreArr: [string, number];
moreArr = ['2', 3]
//可以push元素到元组内
moreArr.push(4);
//不能push元组未定义过的元素类型
// moreArr.push(true);  //error
console.log(moreArr); //['2', 3, 4]

// 不能访问到push进去的元素
// console.log(moreArr[2]); //error

注意:元组的内部元素是可以多样化的,可以是任意类型

4、枚举类型:可以通过值拿到名字
点击查看代码
enum colors1 { green, red, blue };
let col1:colors1 = colors1.blue;
console.log(colors1); // { 0: 'green', 1: 'red', 2: 'blue', green:0, red:1, blue:2 }
console.log(col1); // 2
console.log(colors1[1]); //red

//数字枚举
enum colors2 { green = 1, red, blue };
let col2: colors2 = colors2.red;
console.log(colors2); // { 1: 'green', 2: 'red', 3: 'blue', green:1, red:2, blue:3 }
console.log(col2); // 2 8188
console.log(colors2[2]); //red

//字符串枚举
enum colors3 { green = 'G', red = 'R', blue = 'B' };
console.log(colors3);  //{green: 'G', red: 'R', blue: 'B'}
console.log(colors2.green); //G

//异构枚举
enum colors4 { green = 1, red, blue = 'B' };
console.log(colors4);  //{1: 'green', 2: 'red', green: 1, red: 2, blue: 'B'}
console.log(colors4.red);  //2


//为枚举添加静态方法
enum Month{
  January,
  February,
  March,
  April,
  May,
  June,
  July,
  August,
  September,
  October,
  November,
  December,
}
namespace Month{
  // 判断月份是否是夏季,参数month是可枚举类型
  export function isSummer(month:Month) {
    switch(month) {
      case Month.June:
      case Month.July:
      case Month.August:
        return true;
      default:
        return false;
    }
  }
}

console.log(Month.isSummer(Month.December)); //false

注意:
(1)枚举类型默认是从索引0开始的,也可以手动改变索引从1开始
(2)异构类型在申明时,没有手动设置值的元素会自动被索引匹配
(3)枚举可以是数字枚举也可以是字符串枚举,也可以是混合使用的异构枚举
(4)枚举类型和对象很像,区别在于枚举类型既可以通过枚举名字获取枚举值,也能通过枚举值获取枚举名字;而对象只能通过枚举名字获取枚举值,前者是双向获取,后者只能单向获取

posted @ 2022-02-16 10:13  ~柚子~  阅读(469)  评论(0)    收藏  举报