03. ๐ฆ enum, const enum, as const, keyof, typeof ์ ๋ฆฌ
๐ 1. Enum (์ด๊ฑฐํ)
์ฌ๋ฌ ๊ด๋ จ๋ ๊ฐ๋ค์ ํ๋์ ์ด๋ฆ ์๋์ ๊ทธ๋ฃนํํ ์ ์๋ ํ์ ์คํฌ๋ฆฝํธ์ ๊ธฐ๋ฅ
- ๊ธฐ๋ณธ๊ฐ์ ์ซ์ 0๋ถํฐ ์์ํ์ฌ 1์ฉ ์ฆ๊ฐ
- ์ซ์ ์ด๊ฑฐํ: enum Direction
{ Up = 0, Down = 1 ... }
์ ๋์ผ - ๋ฐํ์์๋ ๊ฐ์ฒด๋ก ์กด์ฌํ๋ฉฐ, ์๋ฐฉํฅ ๋งคํ์ด ๊ฐ๋ฅํจ
//Enum Default
enum EDirection {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
// ์๋ฐฉํฅ ๋งตํ
EDirection.Up; // 0
EDirection[0]; // 'Up'
๐ 2. const enum
๋ฐํ์์๋ ์ ๊ฑฐ๋๊ณ , ์ปดํ์ผ ์ ์ซ์ ๊ฐ์ผ๋ก ์ธ๋ผ์ธ๋จ (์ต์ ํ)
โ์ฃผ์
- const enum์ ๊ฐ์ฒด๊ฐ ๋ฐํ์์ ์์ฑ๋์ง ์์
- ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ฒ๋ผ ์ฌ๋ฌ ๋ชจ๋์์ ์ฌ์ฉํ ๊ฒฝ์ฐ tsconfig์ preserveConstEnums ์ต์ ์ ์ค์ ํ๊ฑฐ๋, ๋์ ๊ฐ์ฒด + as const๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ๊ถ์ฅ
๐ 3. ๋ฌธ์์ด ์ด๊ฑฐํ
- ๊ฐ์ด ๋ฌธ์์ด์ด๋ฉด ์๋ ์ฆ๊ฐ ์์, ๋ชจ๋ ๊ฐ ์๋ ์ง์ ํ์
- JS๋ก ๋ณํ ์ const enum์ด๊ธฐ ๋๋ฌธ์ ๋ฌธ์์ด ์์๋ง ๋จ์
const enum Direction {
Up = "UP",
Down = "DOWN"
}
๐ 4. ๊ฐ์ฒด๋ฅผ enum์ฒ๋ผ ์ฌ์ฉํ๊ธฐ (with as const)
- as const๋ ๊ฐ์ฒด ์์ฑ๋ค์ ๋ฆฌํฐ๋ด ํ์ ์ผ๋ก ๊ณ ์ ํจ (readonly + ์ ํํ ๊ฐ)
- ๋ฐํ์์๋ ๊ฐ์ฒด๊ฐ ์กด์ฌํ๊ธฐ ๋๋ฌธ์ ๋๋ฒ๊น , ์ถ๋ ฅ ๋ฑ์ ์ ๋ฆฌ
- ํ์ ์ถ๋ก ๋ฐ ํ์ฉ์ฑ์ด ์ข๊ธฐ ๋๋ฌธ์ ์ค๋ฌด์์ ๋ ๋ง์ด ์ฌ์ฉ
- as const ๋ ๋ชจ๋ ๊ฐ์ ๋ฆฌํฐ๋ด ํ์ ์ผ๋ก ๊ณ ์ + Read Only
const ODirection = {
Up: 0,
Down: 1,
Left: 2,
Right: 3
} as const;
// ํ์
์ถ๋ก ์, number๋ก ์ฌ์ฉ
const enum EDirection {
UP, //0
Down, //1
Left, //2
Right //3
}
// // JS๋ก ๋ณํ ์ โ const a = 0;
const a = EDirection.Up;
const b = EDirection.Down;
๐ 5. ํ์ ์ง์
Enum์ ํ์ ์ ์ง์ ์ ์ผ๋ก ์ง์ ๊ฐ๋ฅ
const enum EDirection {UP : 0, Down :1, Left : 2, Right : 3,} {
UP = 0,
Down =1,
Left = 2,
Right = 3,
}
//Enum์ ์ง์ ํจ์๋ก์ ์ฌ์ฉ ๊ฐ๋ฅ
function walk(dir: EDirection) {}
๐ 6. ํ์ ์ถ๋ก
- typeof : ๊ฐ์ ํ์ ์ผ๋ก ๋ฐ๊พธ๋ ํค์๋
- keyof : keyof: ๊ฐ์ฒด ํ์ ์ โํคโ๋ง ์ถ์ถํ์ฌ ์ ๋์จ ํ์ ์ผ๋ก ๋ฐํ
const obj = {
a: "apple",
b: "banana"
};
type ObjType = typeof obj;
// ObjType
{
a: string;
b: string;
}
type Keys = keyof ObjType;
// "a" | "b"
// ํ์
์คํฌ๋ฆฝํธ๋ obj๊ฐ '๊ฐ'์ด๊ธฐ ๋๋ฌธ์ ๋ฐ๋ก keyof obj ๋ โ ์ค๋ฅ
type Key = keyof typeof obj;
// โ typeof obj: { a: string; b: string }
// โ keyof { a: string; b: string } โ "a" | "b"
type Key = (typeof obj)[keyof typeof obj];
// typeof obj[keyof typeof obj] โ string ๊ทธ ํ์
์ ๊ฐ์ ํ์
(์ ๋์จ)
// string | string | string โ string
const Direction = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;
typeof Direction
{
readonly Up: 0,
readonly Down: 1,
readonly Left: 2,
readonly Right: 3
}
// ํค ํ์
์ถ๋ก
// keyof typeof Direction
type DirectionKey = keyof typeof Direction
// => 'Up' | 'Down' | 'Left' | 'Right'
// ๊ฐ ํ์
์ถ๋ก
// (typeof Direction)[keyof typeof Direction]
// โ ์ ํค๋ค๋ก ํด๋น ๊ฐ์ฒด ํ์
์ ์ธ๋ฑ์ฑํ๋ฉด ๊ฐ๋ค์ ํ์
์ ๋์จ์ด ๋ฉ๋๋ค.
type DirectionValue = (typeof Direction)[keyof typeof Direction]
// as const๊ฐ ๋ถ์ด์์ ๊ฒฝ์ฐ => 0 | 1 | 2 | 3
// ์์ผ๋ฉด number
//Enum ์ฌ์ฉํ์ง ์๊ณ , ์ฒ๋ฆฌ๋ฅผ ํ์๋
//Value
type Direction = (typeof ODirection)[keyof typeof ODirection] as const
// Key
type Direction = [keyof typeof ODirection] as const
function run(dir: Direction) {}
walk(EDirection.Left)
run(EDirection.Right)
Last updated on