본문 바로가기
언어/TypeScript

enum 자료형

by seacode 2025. 4. 13.

C++을 비롯한 타 언어와 개요는 동일하다.

어떻게 쓰는지만 알아보자.

enum Response {
  a = 100,
  b,
  c,
  d
}

function respond(name: string, msg: Response) {
  console.log(name);
  console.log(msg);
}

respond("mr.kim", Response.c);

숫자, 문자 모두 사용법은 같다. 

단, 문자형 이넘은 숫자형과 다르게 auto incrementing 이 없다.

* 숫자와 문자를 섞어 Heterogeneous Enums 를 쓸 수는 있지만 권장되지는 않는다. 

 

enum 의 특징

1. 런타임 시점

런타임(실행) 할 때, 실제 객체의 형태로써 존재한다.

enum Variables {
  X, Y, Z
}

function getX(obj: { X: number }) {
  return obj.X;
}

getX(Variables); // 0

함수 파라미터로 enum 을 통쨰로 넘겨버렸다. 해당 코드가 컴파일되면 아래와 같은 객체가 생성되기에 정상 동작한다.

// `Variables` 이넘을 컴파일 한 결과
var Variables;
(function (Variables) {
    Variables[Variables["X"] = 0] = "X";
    Variables[Variables["Y"] = 1] = "Y";
    Variables[Variables["Z"] = 2] = "Z";
})(Variables || (Variables = {}));

 

2. 컴파일 시점

- 타입 시스템에 의해서 static check에 사용됨.

- keyof 를 사용해야 할 때는 keyof typeof 를 사용해야한다. (* https://inpa.tistory.com/entry/TS-%F0%9F%93%98-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-keyof-typeof-%EC%82%AC%EC%9A%A9%EB%B2%95)

enum LogLevel {
  ERROR, WARN, INFO, DEBUG
}

// 'ERROR' | 'WARN' | 'INFO' | 'DEBUG';
type LogLevelStrings = keyof typeof LogLevel;

function printImportant(key: LogLevelStrings, message: string) {
    const num = LogLevel[key];
    if (num <= LogLevel.WARN) {
       console.log('Log level key is: ', key);
       console.log('Log level value is: ', num);
       console.log('Log level message is: ', message);
    }
}
printImportant('ERROR', 'This is a message');

 

리버스 맵핑

숫자형에서만 존재하는 맵핑.

key로 value를 얻을 수 있고, 반대도 가능함.

enum Enum {
  A
}
let a = Enum.A; // 키로 값을 획득 하기
let keyName = Enum[a]; // 값으로 키를 획득 하기

'언어 > TypeScript' 카테고리의 다른 글

Class 특성  (0) 2025.04.14
Union Type, Intersection Type  (0) 2025.04.14
인터페이스  (0) 2025.04.13
함수  (0) 2025.04.11
기본 타입  (0) 2025.04.11