ts 元祖/枚举05

元祖

// 元祖 : 合并了不同类型的对象
let Tarr = [123, "123"]; //这里要按位置去添加,第一个是number则数组第一个也要是number类型,string也是如此
// 添加内容的时候,只要是number和string类型就可以了,不能添加除了定义好的类型以外的类型
console.log(Tarr)
Tarr.push("123");
console.log(Tarr)
Tarr.push(999);
console.log(Tarr)

  枚举

// 枚举类型
// 使用枚举给数组赋予名称
enum NumberType {
    one = 2,      //当第一个定义后,后面的数没定义时,会递增+1
    two = 1,
    three,      //当这里递增为2时,会覆盖掉one,所以手动赋值时,尽量不要写重复的值
    four
}
console.log(NumberType)
// 枚举日期案例
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
// 枚举项有两种类型:常数项和计算所得项
// 计算所得项
enum Color {
    Red,
    Green,
    Blue = "blue".length, //当写了计算所得项后就不要写其他东西了,不然会拿不到任何值,除非下一个也是计算所得项,如下
    green = 11
};
// 常数枚举是使用 const enum 定义的枚举类型
// 常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
const enum Obj {
    o,
    b,
    j = 10 + 10,
}
console.log(Obj.o)
console.log(Obj.b)
console.log(Obj.j) //常数枚举在编译阶段时,会直接打印console.log(20 /* Obj.j */);,会计算计算成员
// 外部枚举是使用 declare enum 定义的枚举类型
declare enum ABC { //declare 定义的类型只会用于编译时的检查,编译结果中会被删除
    a, b, c= 10 + 10
}
console.log(ABC.a)
console.log(ABC.b)
console.log(ABC.c) //外部枚举在编译阶段时,会直接打印console.log(ABC.c);,不会编译计算结果
declare const enum AD { //declare 与const两者之间继续结合
    a, b, c= 10 + 10
}
console.log(AD.a)//结合起来的枚举在编译阶段时,会直接打印console.log(0 /* AD.a */);,计算结果会变成0

  上述枚举方法的编译

// 枚举类型
// 使用枚举给数组赋予名称
var NumberType;
(function (NumberType) {
    NumberType[NumberType["one"] = 2] = "one";
    NumberType[NumberType["two"] = 1] = "two";
    NumberType[NumberType["three"] = 2] = "three";
    NumberType[NumberType["four"] = 3] = "four";
})(NumberType || (NumberType = {}));
console.log(NumberType);
// 枚举日期案例
var Days;
(function (Days) {
    Days[Days["Sun"] = 0] = "Sun";
    Days[Days["Mon"] = 1] = "Mon";
    Days[Days["Tue"] = 2] = "Tue";
    Days[Days["Wed"] = 3] = "Wed";
    Days[Days["Thu"] = 4] = "Thu";
    Days[Days["Fri"] = 5] = "Fri";
    Days[Days["Sat"] = 6] = "Sat";
})(Days || (Days = {}));
;
// 枚举项有两种类型:常数项和计算所得项
// 计算所得项
var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 1] = "Green";
    Color[Color["Blue"] = "blue".length] = "Blue";
    Color[Color["green"] = 11] = "green";
})(Color || (Color = {}));
;
console.log(0 /* Obj.o */);
console.log(1 /* Obj.b */);
console.log(20 /* Obj.j */); //常数枚举在编译阶段时,会直接打印console.log(20 /* Obj.j */);,会计算计算成员
console.log(ABC.a);
console.log(ABC.b);
console.log(ABC.c); //外部枚举在编译阶段时,会直接打印console.log(ABC.c);,不会编译计算结果
console.log(0 /* AD.a */); //结合起来的枚举在编译阶段时,会直接打印console.log(0 /* AD.a */);,计算结果会变成0

  

posted @ 2024-02-19 16:40  文采呱呱  阅读(13)  评论(0编辑  收藏  举报