본문 바로가기
TypeScript

[TypeScript] TypeScript에서 new Date() 사용하기

by pocket.dev 2024. 5. 21.
반응형

 

 

 

디데이를 계산하는 함수를 작성하는 도중에 3번째 줄에서 타입스크립트 에러가 발생하였다.

const targetDay = new Date(date);
const today = new Date(Date.now() + KOREA_TIME_DIFFERENCE);
const dayGapMillis = today - targetDay; // today와 targetDay에 붉은선이 생겼다.
const dayGap = Math.floor(dayGapMillis / ONE_DAY_MILLISECONDS);


today와 targetDay를 뺄셈하는 도중에 발생한 에러 내용은 다음과 같다:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.


new Date()로 선언된 오브젝트를 담을 targetDay와 today에 Date형으로 선언해주었으나, 에러는 사라지지 않았다.

const targetDay:Date = new Date(date);
const today:Date = new Date(Date.now() + KOREA_TIME_DIFFERENCE);


에러 내용을 살펴보면 연산 대상은 any, number, bigint, enum 타입 중에 하나여야 한다고 한다. 그래서 .getTime() 메서드를 사용해서 new Date()로 생성한 값을 number형으로 받은 후에 빼기(-) 연산을 하였다. 에러가 사라진 것을 확인하였다.

const dayGapMillis = today.getTime() - targetDay.getTime();


최종 반영본:

const targetDay = new Date(date);
const today = new Date(Date.now() + KOREA_TIME_DIFFERENCE);
const dayGapMillis = today.getTime() - targetDay.getTime();
const dayGap = Math.floor(dayGapMillis / ONE_DAY_MILLISECONDS);