Home
All Posts
✌🏻

[캘린더 라이브러리] undefined가 될 가능성이 있다는 경고를 해결하는 두 가지 방법

Created
2024/03/10
Category
Troubleshoot
3 more properties

에러를 대체하는 방법

TypeScript에서는 모든 변수에 대해 null 또는 undefined를 체크한다. 이 경우 특정 변수가 undefined가 될 가능성이 있다고 경고하는 것이기에, 이를 해결하기 위해서는 해당 변수가 잘 정의되어 있는지 확인하는 코드를 추가해야 한다.

예시 코드 1: 조건문 활용

예를 들어, 아래의 currentDateundefined가 아님을 보장하는 코드는 아래와 같다.
const LeftButton: React.FC<ButtonProps> = ({ setCurrentDate, currentDate }) => { const handlePreviousMonth = () => { if (currentDate) { // currentDate가 정의되어 있으면 해당 로직을 실행하는 조건문 setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1)); } }; return <StyledLeftButton onClick={handlePreviousMonth} />; };
TypeScript
복사

예시 코드 2: 기본값 제공

또 다른 방법으로는 currentDate에 기본값을 제공하는 것이다. 만약 currentDateundefined로 전달되면 기본값으로 new Date()를 사용하도록 할 수 있다.
const LeftButton: React.FC<ButtonProps> = ({ setCurrentDate, currentDate = new Date() }) => { // new Date() 이라는 기본값 제공 const handlePreviousMonth = () => { setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1)); }; return <StyledLeftButton onClick={handlePreviousMonth} />; };
TypeScript
복사
이렇게 하면 currentDateundefined일 때 기본값으로 현재 날짜를 사용하게 된다. 이 방법을 사용하면 추가적인 undefined 체크가 필요 없어 코드가 더 간결해지는 효과가 있겠다.