enum์€ ๋ฌด์—‡์ธ๊ณ ?๐Ÿค”

๐Ÿ’ก enum: ์—ฌ๋Ÿฌ ๊ด€๋ จ๋œ ์ƒ์ˆ˜ ๊ฐ’๋“ค์„ ํ•œ ๊ณณ์— ๋ชจ์•„์„œ ์ •๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ํƒ€์ž…

JavaScript์—์„œ๋Š” enum type์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ, TypeScript์—์„œ ์ €์ฒด์ ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” ํƒ€์ž… ์ค‘ ํ•˜๋‚˜.


โœ”๏ธ enum ์˜ˆ์ œ1

JavaScript์—์„œ, ๋ณดํ†ต ์ƒ์ˆ˜(๋ณ€ํ•˜์ง€ ์•Š๋Š” ์ˆ˜, constant)๋ฅผ ์„ ์–ธํ•  ๋•Œ์—๋Š” ๋ณ€์ˆ˜๋ช…์„ ๋Œ€๋ฌธ์ž๋กœ ์„ ์–ธํ•˜์ง€๋งŒ, TypeScript์—์„œ enum ์„ ์–ธํ•  ๋•Œ์—๋Š” ์ฒซ ๊ธ€์ž๋งŒ ๋Œ€๋ฌธ์ž๋กœ ์„ ์–ธํ•œ๋‹ค.

// JavaScript
const MAX_NUM = 6;
const MAX_STUDENTS_PER_CLASS = 10;

const MONDAY = 0;
const TUESDAY = 1;
const WEDNESDAY = 2;
// JavaScript์—์„œ๋Š” ๊ด€๋ จ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฌถ์„ ์ˆ˜ ์žˆ๋Š” ํƒ€์ž…์ด ๋ณ„๋„ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ, ์•„๋ž˜์ฒ˜๋Ÿผ Object๋กœ ๊ตฌํ˜„.
const DAYS_ENUM = Object.freeze({ MONDAY: 0, TUESDAY: 1, WEDNESDAY: 2 });
const dayOfToday = DAYS_ENUM.MONDAY;

// TypeScript
enum Days {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}
console.log(Days.Monday);

let day: Days = Days.Saturday;
day = Days.Tuesday;

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ enum์„ ์‚ฌ์šฉํ•˜๋ฉด

  • ์„ ํƒํ•œ ๊ฐ’์ด ์ˆซ์ž 0๋ถ€ํ„ฐ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ๊ฐ’์„ ๊ฐ€์ง€๊ฒŒ ๋˜๊ณ 
    • ์˜ˆ์‹œ) console.log(Days.Monday);๋Š” 0์ด ์ถœ๋ ฅ๋จ


  • 0์ด ์•„๋‹Œ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ์ง€์ •ํ•˜๋ฉด ๋œ๋‹ค
    • ์˜ˆ์‹œ) console.log(Days.Monday);๋Š” 1์ด ์ถœ๋ ฅ๋จ


  • ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž์—ด๋„ ์ง€์ •์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
    • ์˜ˆ์‹œ) console.log(Days.Monday);๋Š” monday์ด๊ฐ€ ์ถœ๋ ฅ๋จ


๐Ÿ˜ฑ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ enum์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์ด์œ !!!!!!

enum Days {
  Monday,
  Tuesday,
  Wednesday,
}

let day: Days = Days.Monday;

day = 10; // enum type์ด ์ง€์ •๋œ ๋ณ€์ˆ˜์— ๋‹ค๋ฅธ ์ˆซ์ž๋ฅผ ํ• ๋‹นํ•ด๋„ ์—๋Ÿฌ๊ฐ€ ๋‚˜์ง€ ์•Š๋Š”๋‹ค ๐Ÿ˜ฑ

โœจ tl;dr

๐Ÿ“Œ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ enum ํƒ€์ž…์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ด์œ ๋Š”,

  • enum์œผ๋กœ ํƒ€์ž…์ด ์ง€์ •๋œ ๋ณ€์ˆ˜์— ๋‹ค๋ฅธ ์ˆซ์ž๋ฅผ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์—ฐ๊ด€๋˜์ง€ ์•Š๋Š” ์ˆซ์ž๋„ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๋‹ค.

๋”ฐ๋ผ์„œ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” enum ๋Œ€์‹  union ํƒ€์ž…์„ ์‚ฌ์šฉํ•œ๋‹ค.