-
Typescript에서 특정 key를 가진 타입 생성NodeJS 2024. 6. 25. 17:21728x90
약속된 키만 가진 클래스를 생성하려다 실패했습니다. 검색을 해보니, Type이나, Record를 사용하라고 되어 있네요.
type을 이용한 처리
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; type ChoresMap = { [DAY in DayOfTheWeek]: string }; const chores: ChoresMap = { // ERROR! Property 'saturday' is missing in type '...' "sunday": "do the dishes", "monday": "walk the dog", "tuesday": "water the plants", "wednesday": "take out the trash", "thursday": "clean your room", "friday": "mow the lawn", };
Record 를 이용한 처리
Record는 프로퍼티 키가 Keys이고 프로퍼티 값이 Type인 객체 유형을 생성합니다. 이 유틸리티는 타입의 프로퍼티를 다른 타입에 매핑하는 데 사용할 수 있습니다.
interface CatInfo { age: number; breed: string; } type CatName = "miffy" | "boris" | "mordred"; const cats: Record<CatName, CatInfo> = { miffy: { age: 10, breed: "Persian" }, boris: { age: 5, breed: "Maine Coon" }, mordred: { age: 16, breed: "British Shorthair" }, };
옵션 key 처리
Record은 key를 필수 값으로 만듭니다.
이를 옵션으로 처리 하기 위해서는 Partial을 이용합니다.
코드는 아래와 같습니다.
// type type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; type ChoresMap = { [DAY in DayOfTheWeek]: string }; const chores: Partial<ChoresMap> = { // Partial 을 이용한 옵션 처리 "sunday": "do the dishes", "monday": "walk the dog", }; // 동료가 주신 다른 방법 type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; type ChoresMap = { [DAY in DayOfTheWeek]?: string }; // ? 를 이용하여 옵션으로 변경 const chores: ChoresMap = { "sunday": "do the dishes", }; // Record interface CatInfo { age: number; breed: string; } type CatName = "miffy" | "boris" | "mordred"; const cats: Partial<Record<CatName, CatInfo>> = { // Partial 을 이용한 옵션 처리 miffy: { age: 10, breed: "Persian" }, boris: { age: 5, breed: "Maine Coon" }, };
참고자료
- Enforcing the type of the indexed members of a Typescript object?
- Define a list of optional keys for Typescript Record
728x90'NodeJS' 카테고리의 다른 글
typescript에서의 class, interface 그리고 duck type (0) 2024.06.27 nestjs에서 guard에 Global service Inject 처리 (0) 2024.06.20 [Nestjs TIP] whitelist 사용시 주의점! (0) 2024.06.18 [Nestjs TIP] Request Header에 validate 처리 (0) 2024.06.17 nestjs에서 registerAsync 사용시 isGlobal 설정 (0) 2024.06.12