Enums
In computer
programming, an enumerated type (also called enumeration, enum, or factor in
the R programming language, and a categorical variable in statistics) is a data
type consisting of a set of named values called elements, members, enumeral, or
enumerators of the type(reference wikipedia.org).
Enum allows
us to create set of named constants, common use is we can create distinct
cases. TypeScript provides both numeric and string-based enums.
We can
create three types of enum in typescript
following examples will explain in details , how to create enums.
1. Numeric
enums
We will
start with numeric enums, an enum can be defined using the enum keyword.
Enum Visibility
{
None=1,
Hidden,
Visible
};
Above, we
have a numeric enum where Up is initialized with 1. All the following members
are auto-incremented from that point on. In other words, Visibility.None has
the value 1, Hidden has 2, Visible has 3.
enum Visibility
{
None,
Hidden,
Visible
};
Here, None would
have the value 0
, Hidden would
have 1
, etc. This
auto-incrementing behavior is useful for cases where we might not care about
the member values themselves, but do care that each value is distinct from
other values in the same enum.
How to
use it:
Using an
enum is simple: just access any member as a property off the enum itself, and
declare types using the name of the enum, check following example where we used
enum to set text display mode.
Example:
function
setVisibiity(recipient: string, message: Visibility): void {
// ...
}
setVisibiity("Aditya
Balaji Kendre", Visibility.Visible)
2. String enums
In a string
enum, each member must be constant-initialized with a string literal, or with
another string enum member.
How to use it:
function
SetUserFevColor(recipient: string, userColorChoice: Colors): void {
// ...some typescript custom code
}
SetUserFevColor("Ajay Balaji
Kendre", Colors.Green);
3. Heterogeneous enums
Technically
enums can be mixed with string and numeric members,but its recommended to avoid
Heterogeneous enums except must require case.
Example:
enum
UpdatedData {
No = 0,
Yes="YES"
}