Typescript
νμ μ€ν¬λ¦½νΈ - Enum (μ΄λ)
hyo.loui
2023. 1. 17. 20:35
π―λͺ©μ :
Type Script μ΄λ, μ 리 λ° λ³΅μ΅
1. Enum (μ΄λ) μ΄λ?
JSμλ μκ³ TSμλ§ μλ νμ
νΉμ κ°λ€μ μ§ν©μ μλ―Ένλ μλ£ν
μ½κ² λ§ν΄, νμ ν μ€λΈμ νΈ(κ°μ²΄)μ΄λ€
2. μ«μν μ΄λ
// μ«μν μ΄λ
enum Direction {
Up = 1, // μμ number μ€μ κ°λ₯!
Down,
Left = 200, // μ€λ number νκΈ°μ λ€λ‘ μμ±ν κ²λ€μ (+ 1) μ΄ λλ€
Right,
}
console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); // 1, 2, 200, 201
const up: Direction = Direction.Up;
console.log("ππ up", up); // ππ up 1
const down: Direction = Direction.Down;
console.log("ππ down", down); // ππ down 2
const LeftOrRight: Direction.Left | Direction.Right = Direction.Right;
console.log("ππ LeftOrRight", LeftOrRight); // ππ LeftOrRight 201
console.log(Direction[1]); // Up
3. λ¬Έμν μ΄λ
// λ¬Έμν μ΄λ
enum Direction2 {
Up = "up",
Down = "Down",
Left = "Left",
Right = "Right",
}
console.log(Direction.Down); // 2
4. 볡ν©ν μ΄λ
μλ‘ λ€λ₯Έ νμ μ μ΄λμ λ£μ μ μλ€
νμ§λ§ κΆκ³ νμ§ μλ λ°©λ²μ΄κ³ , μ μ¬μ©νμ§ μλλ€κ³ νλ€
// 볡ν©ν μ΄λ(κΆκ³ νμ§ μμ)
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "yes",
}
console.log(BooleanLikeHeterogeneousEnum.No, BooleanLikeHeterogeneousEnum.Yes); // 0 yes
μμ²λΌ μΈμκ° 1κ°λ§ μ λ¬μ΄ λμ΄λ κΈ°λ³Έκ°μ΄ μκΈ° λλ¬Έμ μλ¬κ° λ°μνμ§ μλλ€.
μ΅μ’ μ 리
- μ΄λμ νΉμ κ°λ€μ μ§ν©μ΄κ³ , νμ ν μ€λΈμ νΈλΌκ³ μκ°νλ©΄ νΈνλ€
- μ«μν μ΄λμμ 첫λ²μ§Έ κ°μ μ«μλ₯Ό λ£μ΄μ£Όλ©΄, μλμΌλ‘ λ€μ μλ κ°μ²΄λ€μ +1μ© λν΄μ€λ€
- λ¬Έμν μ΄λμ μ°λ¦¬κ° κ°μ²΄ μ¬μ©ν λμ κ°μ΄ enum.key λ‘ μΈλΆμμ μ¬μ©ν μ μλ€.
- 볡ν©ν μ΄λμ λ€λ₯Έ νμ μ κ°μ΄ μ΄λμ λ£μ κ²μ΄μ§λ§, μ μ¬μ©νμ§ μλλ€.