- Published on
TypeScript - 枚举
- Authors
- Name
- Deng Hua
目录
Introducing Enums
Enums allow us to define a set of named constants. We can give these constants numeric or string values. There's quite a few options when it comes to enums!
枚举允许我们定义一组命名常量。我们可以给这些常量数字或字符串值。要定义一个枚举类型,请使用enum
关键字。
enum OrderStatus {
PENDING, // (enum member) OrderStatus.PENDING = 0
SHIPPED,
DELIVERED,
RETURNED,
}
const orderStatus = OrderStatus.DELIVERED
function isDelivered(status: OrderStatus) {
return status === OrderStatus.DELIVERED
}
isDelivered
函数的参数为一个枚举类型,它的枚举值可以在类型注释中找到。
创建枚举时,如果不指定任何值,typescript将会分配一个从0
开始的数值。
当然,也可以手动为枚举值赋值。
enum OrderStatus {
PENDING = 1,
SHIPPED = 2,
DELIVERED = 3,
RETURNED = 4,
}
enum ArrowKey {
UP = 'up',
DOWN = 'down',
LEFT = 'left',
RIGHT = 'right',
}
混合类型枚举
enum HybridEnum {
a = 1,
b = 'string',
}