- TypeScript 트랜스파일 환경
- https://www.typescriptlang.org/play
- TypeScript v5.0.4
- JavaScript ESNext
- Tree Shaking 검증
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 트리 쉐이킹
은 사용하지 않는 코드를 제거하여 번들의 사이즈를 줄이는 방식이다.
TypeScript에서 타입을 Enum으로 선언하게 되면 Babel로 컴파일 되면서 즉시실행함수(IIFE)
로 변환된다.
enum Fruits {
Apple,
Banana,
Tomato
}
"use strict";
var Fruits;
(function (Fruits) {
Fruits[Fruits["Apple"] = 0] = "Apple";
Fruits[Fruits["Banana"] = 1] = "Banana";
Fruits[Fruits["Tomato"] = 2] = "Tomato";
})(Fruits || (Fruits = {}));
실제로 쓰이지 않는 코드라도 번들러 입장에서 IIFE는 사용 여부를 판별할 수 없기 때문에 Tree Shaking이 되지 않는다.
const enum Fruits {
Apple = 'Apple',
Banana = 'Banana',
Tomato = 'Tomato'
}
const banana = Fruits.Banana;
"use strict";
const banana = "Banana" /* Fruits.Banana */;
Const Enum을 사용하면 실제로 사용하는 코드만 JavaScript 코드로 변환되기 때문에 Tree Shaking이 가능하다.
하지만 Const Enum은 일반 상수로 선언되기 때문에, 실제 런타임에 실행되는 코드에서 에러를 유발할 수 있다.
이를 방지하기 위해 tsconfig 파일의 compilerOptions에 isolatedModules
설정을 true로 설정할 수 있는데, 이 경우에 const enum 또한 IIFE
가 생성되어 Tree Shaking이 불가능하게 된다.
const Fruits = {
Apple: 'Apple',
Banana: 'Banana',
Tomato: 'Tomato'
} as const;
type Fruits = typeof Fruits[keyof typeof Fruits]; // 'Appla' | 'Banana' | 'Tomato'
"use strict";
const Fruits = {
Apple: 'Apple',
Banana: 'Banana',
Tomato: 'Tomato'
};
Union Types를 사용하면 타입을 정의하는 이점을 그대로 누리면서, JavaScript로 트랜스파일 해도 IIFE가 생성되지 않는다. 따라서 Tree Shaking이 가능해 번들 사이즈를 줄일 수 있다.
상수의 집합이 필요할 경우 Enum 대신 Union Types를 사용하자.
Reference