3.9 열거형
유한한 경우의 수를 갖는 값의 집합을 표현하기 위해 사용하는 열거형(enum) 타입에 대해 배운다.
Last updated
enum InitializedDirection {
East = 2,
West = 4,
South = 8,
North = 16
}enum InitializedDirection2 {
East = 3,
West /* 4 */,
South = 7,
North /* 8 */
}enum Direction {
East = 'EAST',
West = 'WEST',
South = 'SOUTH',
North = 'NORTH'
}function getAnswer() {
return 42;
}
enum SpecialNumbers {
Answer = getAnswer(),
Mystery // error TS1061: Enum member must have initializer.
}enum Direction {
East,
West,
South,
North
}
const east: Direction = Direction.East;var Direction;
(function (Direction) {
Direction[Direction["East"] = 0] = "East";
Direction[Direction["West"] = 1] = "West";
Direction[Direction["South"] = 2] = "South";
Direction[Direction["North"] = 3] = "North";
})(Direction || (Direction = {}));
var east = Direction.East;enum Direction {
East = 'EAST',
West = 'WEST',
South = 'SOUTH',
North = 'NORTH'
}var Direction;
(function (Direction) {
Direction["East"] = "EAST";
Direction["West"] = "WEST";
Direction["South"] = "SOUTH";
Direction["North"] = "NORTH";
})(Direction || (Direction = {}));const enum ConstEnum {
A,
B = 2,
C = B * 2,
D = -C,
}
console.log(ConstEnum.A);console.log(0 /* A */);enum ShapeKind {
Circle,
Triangle = 3,
Square
}type Circle = {
kind: ShapeKind.Circle;
radius: number;
}
type Triangle = {
kind: ShapeKind.Triangle;
maxAngle: number;
}
type Square = {
kind: ShapeKind.Square;
maxLength: number;
}
type Shape = Circle | Triangle | Square;const answer: 42 = 42;
const wrongAnswer: 42 = 24; // error TS2322: Type '24' is not assignable to type '42'.type Direction = 'EAST' | 'WEST' | 'SOUTH' | 'NORTH';
const east: Direction = 'EAST';
const center: Direction = 'CENTER'; // error TS2322: Type '"CENTER"' is not assignable to type 'Direction'.