기타
[기타] ChatGPT 와 친해지기 (3)
mingg123
2023. 2. 10. 15:43
오늘은 TypeScript 관련해서 질문을 해보려고 한다.
export type CalendarFilterOptionType =
| { type: 'recentyear' | 'thisweek' | 'thismonth' }
| { type: 'custom' | 'thistoday'; from: Dayjs; to: Dayjs };
이미 만들어져있는 CalendarFilterOptionType type에서 recentyear, thisweek, thismonth, custon, thistoday 들만 뽑아서 타입으로 사용하고 싶었다.
이런식으로 써도 되지만, 이러면 수정이 일어났을 때 CalendarFilterOptionType, SearchTimeSelect 두 가지를 수정해주어야 한다.
interface SearchTimeSelect {
hour: number;
radio: 'recentyear' | 'thisweek' | 'thismonth' | 'custom' | 'thistoday';
setHour: React.Dispatch<React.SetStateAction<number>>;
}
ChatGPT에게 물어보자.
제법 그럴싸하게 대답해준다. 허나 저런식으로 사용하게 되면 'custom', 'thistoday' 에 걸어놓았던 from, to 의 타입이 엄격하게 검사가 되지 않는다.
ChatGPT에게 다시 물어보았다.
오! 내가원했던 답을 알려준다. 이런식으로 사용하면 CalendarFilterOptionType 타입에서 'recentyear' | 'thisweek' | 'thismonth' | 'custom' | 'thistoday'; 이것들을 뽑아서 사용할 수 있다.
export type CalendarFilterOptionOnly = CalendarFilterOptionType['type'];
이런식으로 훨씬 깔끔하게 사용할 수 있다.
// 수정 전
interface SearchTimeSelect {
hour: number;
radio: 'recentyear' | 'thisweek' | 'thismonth' | 'custom' | 'thistoday';
setHour: React.Dispatch<React.SetStateAction<number>>;
}
// 수정 후
interface SearchTimeSelect {
hour: number;
radio: CalendarFilterOptionType['type'];
setHour: React.Dispatch<React.SetStateAction<number>>;
}