-
2023 - 07 - 25 타입스크립트 ENUM, 객체 리터럴 (Object)Today I Learned/TIL 07 2023. 7. 31. 22:42
타입스크립트 enum을 쓰는 경우와 객체(Object)를 쓰는 경우
enum : 열거형 데이터 타입
상수의 그룹화를 위해선 enum이 좋은 타입이 될 수 있다.
enum 타입은 코드의 가독성을 높이고, 명확한 상수 값을 정의할 수 있다. 또한, 컴파일 시에 자동으로 숫자 값으로 매핑되므로 따로 값을 할당할 필요가 없다.
enum UserRole { ADMIN = "ADMIN", EDITOR = "EDITOR", USER = "USER", } enum UserLevel { NOT_OPERATOR, // 0 OPERATOR // 1 } function checkPermission(userRole: UserRole, userLevel: UserLevel): void { if (userLevel === UserLevel.NOT_OPERATOR) { console.log('당신은 일반 사용자 레벨이에요'); } else { console.log('당신은 운영자 레벨이군요'); } if (userRole === UserRole.ADMIN) { console.log("당신은 어드민이군요"); } else if (userRole === UserRole.EDITOR) { console.log("당신은 에디터에요"); } else { console.log("당신은 사용자군요"); } } const userRole: UserRole = UserRole.EDITOR; const userLevel: UserLevel = UserLevel.NOT_OPERATOR; checkPermission(userRole, userLevel);
객체 리터럴 (Object Literal)
겉으로 보기에 enum과 흡사하나, key-value 쌍으로 구성된 객체를 정의하는 방식이다.
const obj = { a: [1,2,3], b: 'b', c: 4 }
enum의 각 멤버는 상수였기 때문에 number, string 타입의 값만 대입할 수 있다. (하지만, 객체 리터럴에서는 어떤 타입의 값도 대입할 수 있다.)
enum은 간단한 상수 값을 그룹화해서 관리할때 적합하고, enum은 상수 값이기 때문에 각 멤버의 값이 변하면 안된다는 조건이 있다.
하지만 객체 리터럴은 멤버의 값이나 데이터 타입을 마음대로 변경할 수 있으므로, 복잡한 구조와 다양한 데이터타입을 사용해야 할 때는 객체 리터럴을 사용한다.
'Today I Learned > TIL 07' 카테고리의 다른 글
2023 - 07 - 27 타입스크립트 별다방 프로젝트 - 1 (0) 2023.07.31 2023 - 07 - 26 타입스크립트 유틸리티 타입 (Partial, Required, Readonly, Pick, Omit), 선택적 속성 (0) 2023.07.31 2023 - 07 - 24 TypeScript 타입스크립트 const, readonly, any, unknown, union (1) 2023.07.27 2023 - 07 - 23 타입스크립트 TypeScript - 기본 타입, boolean, number, string, 배열, 템플릿리터럴, 튜플, tuple, enum (0) 2023.07.27 2023 - 07 - 22 ES6 소프트웨어 아키텍쳐 (0) 2023.07.27