728x90
Type Script 열거형(Enums)
numberEnum
📄 index.ts
enum Color {
Red,
Green,
Blue,
}
console.log("---------")
const myColor = Color.Red;
console.log(myColor); // 0
const yourColor = Color.Green;
console.log(yourColor) // 1
const myNewColor = Color.Blue;
console.log(myNewColor) // 2
console.log("---------")
console.log(Color["Green"]) // 1
// reverse mapping
console.log(Color[0]) // Red
console.log(Color[2]) // Blue
📌 reverse mapping이 가능한 이유
console.log(Color)
---------------------------------------------------------------------
{ '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
stringEnum
📄 types/index.ts
export enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
📄 index.ts
import { Color } from "./types";
const faveColor: Color.Red = Color.Red;
console.log(faveColor);
const chorock: Color = Color.Green;
console.log(chorock);
함수 사용
📄 others/function.ts
// enums
import { Color, Direction } from "../types";
// interface
import type { ThingsInLife } from "../types"
function printThingsInLife(things: ThingsInLife): string {
return `color of pen: ${things.colorOfPen} keyboard arrow: ${things.keyboardArrow}`
}
console.log(printThingsInLife({ colorOfPen: Color.Blue, keyboardArrow: Direction.Left }))
📄 types/index.ts
export enum Direction {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right",
}
// type TThingsInLife {
// colorOfPen: Color;
// keyboardArrow: Direction;
// };
export interface ThingsInLife {
colorOfPen: Color;
keyboardArrow: Direction;
}
Objects
📄 others/objects.ts
import { Color } from "./types";
const keys = Object.keys(Color);
console.log(keys); // [ 'Red', 'Green', 'Blue' ]
console.log("----------");
const values = Object.values(Color);
console.log(values); // [ 'Red', 'Green', 'Blue' ]
const keyValues = Object.entries(Color);
// [ [ 'Red', 'Red' ], [ 'Green', 'Green' ], [ 'Blue', 'Blue' ] ]
console.log(keyValues);
type ObjectType = {
[key in Color]?: string
};
const myObject: ObjectType = {};
values.forEach((key) => {
myObject[key] = "hello";
});
console.log(myObject); // { Red: 'hello', Green: 'hello', Blue: 'hello' }
enum을 객체의 key값으로 설정
type TableData = {
[x: string]: string;
};
const enum TableKey {
ID = "ID",
firstName = "firstName",
LastName = "lastName",
Score = "score",
}
type StrictTableData = { [key in TableKey]: string };
type LessStrictTableData = { [key in TableKey]?: string }; // string | undefined
const myTableData: LessStrictTableData = {
ID: "1",
firstName: "jane",
lastName: "doe",
};
console.log(myTableData);
Enum과 tree-shaking
// index.ts
enum Color {
Red = 'Red',
Green = 'Green',
Blue = 'Blue',
}
// 쓰이지 않는 enum을 트랜스파일 해보면...
// index.js
"use strict";
var Color;
(function (Color) {
Color["Red"] = "Red";
Color["Green"] = "Green";
Color["Blue"] = "Blue";
})(Color || (Color = {}));
이런한 enum이 엄청나게 많아지면, 사용하지도 않는 부분까지 트렌스쉐이킹되어 버린다.
// index.ts
const enum Color {
Red = 'Red',
Green = 'Green',
Blue = 'Blue',
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const green = "Green" /* Color.Green */;
앞에 const만 붙였을 뿐인데 깔끔하게 트렌스 쉐이킹이 된걸 확인할 수 있다.
js로 번들되는 코드 양을 줄일 수 있다.
Enum 사용시 유리한 응용법
📌 Enum 분해 할당
import { Color } from "./types"
const { Red, Green, Blue: ImBlue } = Color;
const green = Green; // Color.Green
const veggies = Green; // Color.Green
const pepper = Red; // Color.Red
const sky = ImBlue; // Color.Blue
console.log(sky);
// DRY (Don't Repeat Yourshelf!)
'JavaScript' 카테고리의 다른 글
TS Utility Types (0) | 2023.01.27 |
---|---|
Type Script 제너릭타입(Generic types) (0) | 2023.01.26 |
TS, 내가 만든 포켓몬 크롤링 프로그램 (0) | 2023.01.19 |
후발대_node.js 숙력주차 과제 복습 (0) | 2023.01.19 |
타입스크립트 기초문법2 (0) | 2023.01.18 |