This article will introduce you to the Enum (enumeration) syntax in TypeScript, talk about the basic usage of Enum, and how to use native JavaScript to implement Enum.
Enum is a new syntax in TypeScript, also called enumeration. It is generally used to manage multiple Constants of the same series (that is, variables that cannot be modified) are used for status judgment.
A common status judgment in the Web is to handle different response status codes accordingly when processing requests:
const handleResponseStatus = (status: number): void => { switch (status) { case 200: // 请求成功时 // Do something... break; case 400: // 请求失败时 // Do something... break; default: throw (new Error('No have status code!')); } };
But because the response status codes are all pre-defined , so there is no controversy. It is normal for the code to be written like this. However, if the backend customizes some codes when an error occurs on the server and tells the frontend what errors these codes represent, then the above function may become like this:
const handleWrongStatus = (status: string): void => { switch (status) { case 'A': // Do something... break; case 'B': // Do something... break; case 'C': // Do something... break; default: throw (new Error('No have wrong code!')); } };
If it’s this kind of code, let alone someone who just took over it, even if you wrote it two weeks ago, you probably won’t be able to remember what they represent without looking through the document.
But if you make good use of Enum, you can avoid the above situation.
Let’s first look at how to define Enum. It is very similar to Object in usage:
enum requestStatusCodes { error, success, }
There is no need to add an equal sign between the content and the name. Directly describe the variables in the Enum within the curly brackets. It is more appropriate to call them constants rather than variables. Because the values in the Enum cannot be modified, there is no need to worry about these defined rules being executed in the code. Changes occurred during the process, resulting in execution errors.
And since Enum is used to define the same series of constants, these constants should be able to maintain specific values. That's right, every constant in Enum can specify a specific value through =
.
But if it is like the previous requestStatusCodes
, there will be no error if no specific value is specified for error
or success
, because TypeScript will start from 0
starts to automatically increment the defined value, so the signed requestStatusCodes
will have the same result as the following:
enum requestStatusCodes { error = 0, success = 1, }console.log(requestStatusCodes.error) // 0 console.log(requestStatusCodes.success) // 1
In addition to numbers, it can also be defined as a string:
enum requestWrongCodes { missingParameter = 'A', wrongParameter = 'B', invalidToken = 'C', }console.log(requestWrongCodes.wrongParameter) // 'B'
Of course you can also set different types in one enum, but this makes no sense at all:
enum requestStatusCodes { error = 0, success = 'OK', }
After understanding how to define the basic Enum, then rewrite the ## in the previous code #handleResponseStatus and
handleWrongStatus to make them semantically clearer.
enum requestStatusCodes { error = 400, success = 200, } enum requestWrongCodes { missingParameter = 'A', wrongParameterType = 'B', invalidToken = 'C', }
handleResponseStatus and
handleWrongStatus:
const handleResponseStatus = (status: number): void => { switch (status) { case requestStatusCodes.success: // Do something... break; case requestStatusCodes.error: // Do something... break; default: throw (new Error('No have status code!')); } }; const handleWrongStatus = (status: string): void => { // 如果觉得 requestWrongCodes.missingParameter 太长了,也可以用以下方式: const { missingParameter, wrongParameterType, invalidToken, } = requestWrongCodes; switch (status) { case missingParameter: // Do something... break; case wrongParameterType: // Do something... break; case invalidToken: // Do something... break; default: throw (new Error('No have wrong code!')); } };
const newEnum = (descriptions) => { const result = {}; Object.keys(descriptions).forEach((description) => { result[result[description] = descriptions[description]] = description; }); return result; }; const responseStatus = newEnum({ error: 400, success: 200, }); // { '200': 'success', '400': 'error', error: 400, success: 200 } console.log(responseStatus);
constant feature of Enum is lost. If it cannot be made unmodifiable, it may be inadvertently changed in the code, resulting in possible errors in the execution result. So you can use Object.freeze() at the end so that external operations cannot add, delete or redefine any Property:
const newEnum = (descriptions) => { const result = {}; Object.keys(descriptions).forEach((description) => { result[result[description] = descriptions[description]] = description; }); return Object.freeze(result); }; const responseStatus = newEnum({ error: 400, success: 200, }); // 即使不小心修改了 responseStatus['200'] = 'aaaaaaaa'; // 仍然是 { '200': 'success', '400': 'error', error: 400, success: 200 } console.log(responseStatus);
But if you declare Enum with const, Object will not be generated after compilation.
responseState with
const, and also use the Enum to make judgments with
handleResponseStatus:
enum responseStatus { error = 400, success = 200, } const handleResponseStatus = (status: number): void => { switch (status) { case responseStatus.success: console.log('请求成功!'); break; case responseStatus.error: console.log('请求失败!'); break; default: throw (new Error('No have status code!')); } };
const to declare the value in Enum.
const to declare Enum:
const will not generate Object, so there will be no above problems.
就算到的 Enum 不多,判断时也需要一直从 Object 中找出对应的值,而如果是用 const
声明 Enum ,在编译成 JS 时就将声明的值直接放入判断中。
不过这样也就没法从 Enum 中反向取值了,因为它并不会产生对象:
const enum responseStatus { error = 400, success = 200, }// 会出错,因为已经没有对象可供查找了 console.log(responseStatus[400])// 但这个不会有问题,因为编译的时候会直接填值 console.log(responseStatus.error)// 编译后: // console.log(400)
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Let's talk about the usage of Enum (enumeration) in TypeScript. For more information, please follow other related articles on the PHP Chinese website!