TypeScript之枚举

什么是枚举类型,有什么作用?

枚举类型就是一个用来组织一些有相似之处的常量的对象,作用就是管理常量,让常量更规范,统一。例:

 enum Direction { Up = 1, Down, Left, Right }

使用时直接用“.”的方式使用:

Direction.Up、Direction.Down ...

枚举类型的特点:

1.手动赋值时从第一个开始自动赋值0,后来依次+1,

2.未手动赋值的项只能在第一个,或只能在赋值为数字的项的后面,

3枚举的键值对会被翻转声明(反向映射)

存疑:

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

官方文档

enum ShapeKind { Circle, Square, }

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

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

let c: Circle = {

kind: ShapeKind.Square,  // 这里写任何数字都能通过编译,why

// ~~~~~~~~~~~~~~~~ Error!

radius: 100, }

posted @ 2019-11-06 17:54  superjsman  阅读(595)  评论(0编辑  收藏  举报