타입스크립트에서 객체의 key값에 enum을 사용하기 위한 예제입니다.
📁 types/users.ts
export enum GradeScope {
ETC = 'etc',
SILVER = 'silver',
GOLD = 'gold',
PLATINUM = 'platinum',
}
import { GradeScope } from '../types/users';
const gradeMap: { [key in GradeScope]: number } = {
[GradeScope.ETC]: 0,
[GradeScope.SILVER]: 1,
[GradeScope.GOLD]: 2,
[GradeScope.PLATINUM]: 3,
};
만약 모든 키를 포함하지 않으려면, 옵셔널로 사용해줍니다.
import { GradeScope } from '../types/users';
const gradeMap: { [key in GradeScope]?: number } = {
[GradeScope.SILVER]: 1,
[GradeScope.PLATINUM]: 3,
};
참고
Use Enum as restricted key type in Typescript
Can enum be used as a key type instead of only number or string? Currently it seems like the only possible declaration is x:{[key:number]:any} where key can be of type number or string. Is it possi...
stackoverflow.com
[TS] 객체의 key값으로 enum 사용하기 (Use Enum as restricted key type in Typescript)
타입스크립트에서 객체의 key 값으로 enum을 사용하고자 하는 경우 enum MyColor { RED = 0, GREEN = 1, BLUE = 2 } const colorText: { [key in MyColor]: string } = { [MyColor.RED]: '레드', [MyColor.GREEN]: '그린', [MyColor.BLUE]: '블
koreansimpson.tistory.com
'프론트엔드 > Typescript' 카테고리의 다른 글
Typescript Destructuring (0) | 2022.12.04 |
---|