[TypeScript] Enum의 Tree Shaking (Enum vs Const Enum vs Union Types)

suno·2023년 4월 26일
1

Enum이란?

Enum은 이름이 있는 상수들의 집합을 정의한다.
Enum을 사용하면 의도를 문서화 하거나 구분되는 사례 집합을 더 쉽게 만들수 있다.
TypeScript는 숫자와 문자열-기반 Enum을 제공한다.

참고

  • 런타임에서 Enum은 실제 존재하는 객체이고 일반 객체와 동일하게 동작한다.

  • 컴파일 시점에서 keyof typeof 키워드를 사용하면 모든 Enum의 키를 문자열로 나타내는 타입을 가져온다.

    enum LogLevel {
      ERROR,
      WARN,
      INFO,
      DEBUG,
    }
    
    /**
      * 이것은 아래와 동일합니다. :
      * type LogLevelStrings = '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");

Tree Shaking 비교

Tree Shaking 트리 쉐이킹은 사용하지 않는 코드를 제거하여 번들의 사이즈를 줄이는 방식이다.


1. Enum

TypeScript에서 타입을 Enum으로 선언하게 되면 Babel로 컴파일 되면서 즉시실행함수(IIFE)로 변환된다.

TypeScript

enum Fruits {
  Apple,
  Banana,
  Tomato
}

JavaScript

"use strict";
var Fruits;
(function (Fruits) {
  Fruits[Fruits["Apple"] = 0] = "Apple";
  Fruits[Fruits["Banana"] = 1] = "Banana";
  Fruits[Fruits["Tomato"] = 2] = "Tomato";
})(Fruits || (Fruits = {}));

Tree Shaking

실제로 쓰이지 않는 코드라도 번들러 입장에서 IIFE는 사용 여부를 판별할 수 없기 때문에 Tree Shaking이 되지 않는다.


2. Const Enum

TypeScript

const enum Fruits {
  Apple = 'Apple',
  Banana = 'Banana',
  Tomato = 'Tomato'
}
const banana = Fruits.Banana;

JavaScript

"use strict";
const banana = "Banana" /* Fruits.Banana */;

Tree Shaking

Const Enum을 사용하면 실제로 사용하는 코드만 JavaScript 코드로 변환되기 때문에 Tree Shaking이 가능하다.

하지만 Const Enum은 일반 상수로 선언되기 때문에, 실제 런타임에 실행되는 코드에서 에러를 유발할 수 있다.

이를 방지하기 위해 tsconfig 파일의 compilerOptions에 isolatedModules 설정을 true로 설정할 수 있는데, 이 경우에 const enum 또한 IIFE가 생성되어 Tree Shaking이 불가능하게 된다.


3. Union Types

TypeScript

const Fruits = {
  Apple: 'Apple',
  Banana: 'Banana',
  Tomato: 'Tomato'
} as const;
type Fruits = typeof Fruits[keyof typeof Fruits]; // 'Appla' | 'Banana' | 'Tomato'

JavaScript

"use strict";
const Fruits = {
  Apple: 'Apple',
  Banana: 'Banana',
  Tomato: 'Tomato'
};

Tree Shaking

Union Types를 사용하면 타입을 정의하는 이점을 그대로 누리면서, JavaScript로 트랜스파일 해도 IIFE가 생성되지 않는다. 따라서 Tree Shaking이 가능해 번들 사이즈를 줄일 수 있다.


결론

상수의 집합이 필요할 경우 Enum 대신 Union Types를 사용하자.


Reference

profile
Software Engineer 🍊

0개의 댓글