Enums in Typescript

Author
By Darío Rivera
Posted On in TypeScript

The Enum data type in TypeScript allows defining a set of values within a stack. It's very useful when defining interfaces or type aliases. To define this data type, we can use the reserved word Enum as we will see below.

Declaration

We define an Enum as if we were defining an interface, but we will only define the values ​​it contains, not its type.

enum UserType {
    Admin,
    Guest
}

To use this data type, we only need to reference it as shown below.

interface User {
    type: UserType;
    name: string;
}

Initialization

As expected, as it happens in the C language, if the enum values ​​are not specified, integers are assumed starting from zero. See in the following example how the zero value is used to reference the Admin value ​​defined in the enum.

function print_hello(user: User): string
{
    return 'Hello ' + user.name;
}

print_hello({
    type: 0,     // Admin
    name: 'Steve'
})

Of course, this is merely illustrative, you can always pass the value by calling the enum type directly like this:

print_hello({
    type: UserType.Admin,
    name: 'Steve'
})

TypeScript also allows defining enums with string values, for this, it is enough to assign the type like this:

enum UserType {
    Admin = 'Admin',
    Guest = 'Guest'
}

interface User {
    type: UserType;
    name: string;
}

function print_hello(user: User): string
{
    return 'Hello ' + user.name;
}

print_hello({
    type: UserType.Admin,
    name: 'Steve'
})

Although internally the code is transpiled using a character string, the type reference and not the string literal must be used. The following would be incorrect.

print_hello({
    type: 'Admin',
    name: 'Steve'
})

Whenever we define enums in this way, we must refer to them with dot notation.

UserType.Admin

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.