ReasonJun

Typescript : additional provided types (Enum) 본문

Frontend/Typescript

Typescript : additional provided types (Enum)

ReasonJun 2023. 6. 17. 15:19
728x90

In TypeScript, an enum is a special "class" that represents a group of constants (unchangeable variables). Enums come in two flavors string and numeric.

 

enum means enumerated type. An enum names a set of values and makes them available. Here we can utilize an enum to use a set called PrintMedia with a friendly name instead of a hard-to-remember number. Each PrintMedia enumerated is zero-based by default unless a different value is set.

enum PrintMedia {
	Newspapaer, //0
	Newsletter, //1
	Magazine //2
}

Here is an example of a numeric enum:

enum Direction {
  Up = 1,
  Down = 2,
  Left = 3,
  Right = 4,
}

This enum defines four constants, Up, Down, Left, and Right. The values of these constants are 1, 2, 3, and 4, respectively.

Enums can also be used with strings:

enum Color {
  Red = "Red",
  Green = "Green",
  Blue = "Blue",
}

enum means enumerated type. An enum names a set of values and makes them available. Here we can utilize an enum to use a set called PrintMedia with a friendly name instead of a hard-to-remember number. Each PrintMedia enumerated is zero-based by default unless a different value is set.

Looking at it like this, there seems to be no difference between using enum and JS object. In fact, enums are also objects themselves.

 

So when you do Object.keys(LanguageCode) , the actual key values come out in an array. => ['korean', 'english'].

If you do Object.values(LanguageCode) , value will be ... => ['ko', 'en'].

Difference between enum and object

An object is free to add new properties in code, but an enum cannot be changed after it is declared.

Object property values can be of any type allowed by JS, but only strings or numbers are allowed as enum property values.

728x90
Comments