- Learn React with TypeScript 3
- Carl Rippon
- 295字
- 2021-06-10 19:16:33
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:
- Let's declare an enum for order statuses in the TypeScript playground:
enum OrderStatus {
Paid,
Shipped,
Completed,
Cancelled
}
- 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.
- 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:
- 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
}
- 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:
- 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.
推薦閱讀
- Mastering JavaScript Object-Oriented Programming
- 軟件界面交互設(shè)計(jì)基礎(chǔ)
- Hands-On Data Structures and Algorithms with JavaScript
- Linux網(wǎng)絡(luò)程序設(shè)計(jì):基于龍芯平臺(tái)
- C程序設(shè)計(jì)案例教程
- Apex Design Patterns
- C語言程序設(shè)計(jì)案例精粹
- HTML5+CSS3網(wǎng)頁設(shè)計(jì)
- C語言開發(fā)基礎(chǔ)教程(Dev-C++)(第2版)
- C語言程序設(shè)計(jì)
- Modern C++ Programming Cookbook
- 算法圖解
- Python全棧開發(fā):基礎(chǔ)入門
- Python深度學(xué)習(xí)與項(xiàng)目實(shí)戰(zhàn)
- Go語言編程之旅:一起用Go做項(xiàng)目