TypeScript枚举

枚举:使用enum 定义一些带名字的常量。 使用枚举可以清晰地表达意图或创建一组有区别的用例。 TypeScript支持数字的和基于字符串的枚举。

数字枚举

初始化一个枚举,其他枚举会自增长

enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}
console.log(Direction.Up)
console.log(Direction[1])

字符串枚举

每个成员都必须进行初始化

enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}
console.log(Direction.Up)
console.log(Direction['Right'])

异构枚举

枚举可以混合字符串和数字成员,一般不会使用此种情况

enum Direction {
    Up = 1,
    Down = 'Down',
    Left = 2,
    Right = 'Right'
}
console.log(Direction.Up)
console.log(Direction[1])  // 反向映射

联合枚举与枚举成员的类型

enum ShapeKind {
    Circle,
    Square,
}

interface Circle {
    kind: ShapeKind.Circle;
    radius: number;
}

interface Square {
    kind: ShapeKind.Square;
    sideLength: number;
}

let c: Circle = {
    kind: ShapeKind.Square, // 不能将类型“ShapeKind.Square”分配给类型“ShapeKind.Circle”
    radius: 100,
};

运行时的枚举

enum E {
    X, Y, Z
}
function f(obj: { X: number }) {
    return obj.X;
}

console.log(f(E))  // 0

反向映射

除了创建一个以属性名做为对象成员的对象之外,数字枚举成员还具有了 反向映射,从枚举值到枚举名字

const枚举

常量枚举不允许包含计算成员

const enum Directions {
    Up,
    Down,
    Left,
    Right 
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]

外部枚举

外部枚举和非外部枚举之间有一个重要的区别,在正常的枚举里,没有初始化方法的成员被当成常数成员。 对于非常数的外部枚举而言,没有初始化方法时被当做需要经过计算的。

declare enum Directions  {
    A = 1,
    B,
    C = 2
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山为樽水为沼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值