One of the concepts that exist in TypeScript is a type of data that has a dual state (like tuples
). This type of data is usually used to assign a numerical value that has a string to be read by humans and is called an Enum
. Enum
s are available in many programming languages, but we don't have access to them in JavaScript.
To write an Enum
, you must use the following structure:
Enum name {NEW, OLD}
For today's exercise, I use the following code:
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author']
};
I want to change the role
. Suppose we have three levels of admin
, author
and reader
(normal users) for the role (user's role on the site). Now we want to have a numerical value for each of these roles to use in the code: admin
is 0
, normal user is 1
, and author
is 2
.
Question: Why not add numbers normally? For example, in the form of an array?
Answer: Because our possible problems increase. For example, we may add a number that is not defined in the system (for example, level 4 that does not exist). Another example is our own work. If we put the numbers in an array normally, during development we would have to constantly check who each access level was for.
Usually, newbies try to avoid numbers and use strings like Admin
or ReadOnly-User
to make the code more readable, but the problem is that during coding, for example, in if
conditions, they remember that the defined value is Read-only-user
or read_only_user
or ReadOnlyUser
or... That's why constants are usually used in JavaScript, for example:
const ADMIN = 'ADMIN';
const USER = 'READ-ONLY-USER';
const AUTHOR = 3;
Then these same constants are used instead of writing strings. This method is a suitable method, but it is still possible to enter an invalid value in them by mistake, because, for example, in the code above, AUTHOR
has the data type number
, so we can put any number in its place!
Now suppose we want to write an enum
for this situation:
enum Role { ADMIN = 'ADMIN', READ_ONLY = 100, AUTHOR = 'AUTHOR' };
Usually, in coding conventions, it is said that the enum
name must start with a capital letter (Role
) and the values inside it must all be written in capital letters (READ_ONLY
and...). As you can see, you can use numbers and strings and whatever you want, just like arrays.
Also note that we can write the above example as follows:
enum Role { ADMIN, READ_ONLY, AUTHOR };
In this case, index
is used as a value, that is, ADMIN
is equal to zero
, READ_ONLY
is equal to one
, and AUTHOR
is equal to 2
, but if you want to use a value other than the default indexes, which are numeric, you can use the example above. Use it and give it your own desired values.
Also, if you only define a separate number for the first value, the Enum starts there:
enum Role { ADMIN = 5, READ_ONLY, AUTHOR };
Here I have set ADMIN
to be 5
so READ_ONLY
value is 6
and AUTHOR
value is 7
. That is, initialization starts from the first number. Note that the name of each of these items (such as ADMIN
) is a type of label, which means we only use it to work in the code. For example, in the above code, ADMIN
is equal to 5
, so wherever we use Role.ADMIN
, the number 5
is given to us, not the string ADMIN
. This can cause you to make mistakes in string mode.
We can use it as an example to say:
enum Role { ADMIN, READ_ONLY, AUTHOR };
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: Role.ADMIN
};
Then, to try the codes, you can say:
if (person.role === Role.AUTHOR) {
console.log('is author');
}
Since above we had set the value of Role.ADMIN
for the role
, the console.log
statement should not be executed and if we go to the browser, I will not see anything. Why? Because ADMIN
is not the same as AUTHOR
and the condition is wrong.
In addition, as I said, Enums are only in Typescript and do not exist externally in JavaScript, so if you run the tsc app.ts
command and go to the app.js
file, you will easily notice the differences:
let Role;
(function (Role) {
Role["ADMIN"] = "ADMIN";
Role[Role["READ_ONLY"] = 100] = "READ_ONLY";
Role["AUTHOR"] = "AUTHOR";
})(Role || (Role = {}));
;
var person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: Role.ADMIN
};
As you can see, implementing our simple code in JavaScript is complicated and time-consuming, and this is one of the beauties of the TypeScript language, which makes our work much easier.
any
type in typescript
any
means "anything", so if you give this type to any variable, it means that you have allowed any value to be placed in it. Pay attention to the following example:
let favoriteActivities: any;
The favoriteActivities
variable can take any value and there will be no problem. Using any
is not recommended because it takes away the benefits of TypeScript. At least we can say instead of any
:
let favoriteActivities: any[];
In this case, at least we say that it is an array that accepts any value in itself so that we are a little more limited. any
has no special explanation and is really that simple. Note that most programmers recommend that you avoid any
as much as possible unless you don't know what value one of your variables is going to take. In such a situation, you can temporarily use any
to avoid making a mistake and then come back in the future and choose the correct type for it.
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.
Hello,
this Comment has been upvoted with 100%, thanks to @albro who burned 1000 PLANET
With this burn @albro is actively participating in the CLEAN PLANET reward protocol.
@albro is helping @cleanplanet to grow with the curation.
Thanks for your help
@cleanplanet