Using Enums in TypeScript: A Beginner's Guide

TypeScript enums, or enumerations, are a way to define a set of named constants. They allow you to give a name to a set of numeric values, which can make your code more readable and maintainable.

Here is an example of how to define an enum in TypeScript:

enum Role {
Admin,
Member,
Guest
}

In this example, we have defined an enum called Role with three members: Admin, Member, and Guest. Each member is assigned a numeric value, starting with 0 for Admin and incrementing by 1 for each subsequent member. So, Member is assigned the value 1 and Guest is assigned the value 2.

You can access the members of an enum using dot notation. For example:

let role = Role.Admin;

In this code, the role variable is assigned the value of the Admin member of the Role enum, which is 1.

You can also specify the values for the members of an enum explicitly, like this:

enum Role {
Admin = 'admin',
Member = 'member',
Guest = 'guest'
}

Enums can be a useful tool for making your code more readable and maintainable. They can also help prevent errors by ensuring that only valid values are assigned to variables.

Here is an example of how to use an enum as a type in TypeScript:

enum Role {
Admin = 'admin',
Member = 'member',
Guest = 'guest'
}
let role: Role = Role.Admin;

In this code, we have declared a variable called myColor and assigned it the value of the Admin member of the Role enum. We have also specified that role has the type Role, which means that it can only be assigned a value from the Role enum.

This means that if we try to assign a value to role that is not a member of the Role enum, we will get a compile-time error. For example, the following code would not be allowed:

let role: Role = 'admin' // Type Error: Type '"admin"' is not assignable to type 'Role'

Let's take a look at how to use an enum as an argument of a function in TypeScript:

enum Role {
Admin = 'admin',
Member = 'member',
Guest = 'guest'
}
function getPermission(role: Role): string {
switch (role) {
case Role.Admin:
return 'full';
case Role.Member:
return 'edit';
case Role.Guest:
return 'view';
default:
return 'permission denied';
}
}
let myRole = Role.Admin;
let permission = getPermission(myRole); // 'full'

In this code, we have defined a function called getPermission() that takes a role argument of type Role. The function returns the permission of the role as a string.

Finally, we have declared a variable called myRole and assigned it the value of the Admin member of the Role enum. We have then passed myRole as an argument to the getPermission() function, and assigned the return value to the permission variable.

As you can see, using enums as arguments of functions can make your code more readable and maintainable. It can also help prevent errors by ensuring that only valid values are passed to the function.


December 05, 2022
16