官术网_书友最值得收藏!

Enumerations

Enumerations allow us to declare a meaningful set of friendly names that a variable can be set to. We use the enum keyword, followed by the name we want to give to it, followed by the possible values in curly braces.

Here's an example:

  1. Let's declare an enum for order statuses in the TypeScript playground:
enum OrderStatus {
Paid,
Shipped,
Completed,
Cancelled
}
  1. If we look at the transpiled JavaScript, we see that it looks very different:
var OrderStatus;
(function (OrderStatus) {
OrderStatus[OrderStatus["Paid"] = 1] = "Paid";
OrderStatus[OrderStatus["Shipped"] = 2] = "Shipped";
OrderStatus[OrderStatus["Completed"] = 3] = "Completed";
OrderStatus[OrderStatus["Cancelled"] = 4] = "Cancelled";
})(OrderStatus || (OrderStatus = {}));

This is because enumerations don't exist in JavaScript, so the TypeScript compiler is transpiling the code into something that does exist.

  1. Let's declare a status variable, setting the value to the shipped status:
let status = OrderStatus.Shipped; 

Notice how we get nice IntelliSense when typing the value:

  1. By default, the numerical values start from 0 and increment. However, the starting value can be explicitly declared in the enum, as in the following example, where we set Paid to 1:
enum OrderStatus {
Paid = 1,
Shipped,
Completed,
Cancelled
}
  1. Let's set our status variable to the shipped status and log this to the console:
let status = OrderStatus.Shipped;
console.log(status);

If we run the program, we should see 2 output in the console:

  1. In addition, all the values can be explicitly declared, as in the following example:
enum OrderStatus {
Paid = 1,
Shipped = 2,
Completed = 3,
Cancelled = 0
}

Enumerations are great for data such as a status that is stored as a specific set of integers but actually has some business meaning. They make our code more readable and less prone to error.

主站蜘蛛池模板: 武陟县| 宝清县| 寿宁县| 镶黄旗| 弥勒县| 旺苍县| 二连浩特市| 峨山| 鄄城县| 华坪县| 准格尔旗| 高唐县| 高雄县| 睢宁县| 崇义县| 长葛市| 佛冈县| 丁青县| 临泽县| 伽师县| 金昌市| 台湾省| 阿拉善左旗| 舒城县| 遂川县| 福鼎市| 甘肃省| 大姚县| 安康市| 大竹县| 从化市| 余江县| 平潭县| 洪洞县| 西和县| 巫溪县| 霍山县| 霍城县| 丰城市| 昭苏县| 漳浦县|