[TypeScript Error] The left-hand side of an arithmetic operation must be of type ‘any’ ‘number’ or an enum type (TS2363)

고병표·2022년 2월 13일
0

Error 모음

목록 보기
8/13
post-thumbnail

🤔 The left-hand side of an arithmetic operation must be of type ‘any’ ‘number’ or an enum type (TS2363)

TS에서 sort 함수를 이용하여 배열을 날짜순으로 정렬할때 발생하였다.

arr.sort(a: IMessageData, b: IMessageData): number => new Date(a.date) - new Date(b.date)

위 코드는 js 코드에선 문제가 없었지만, new Date()를 연산하는 과정에서 에러가 발생한다

그 이유는 Date()로 생성한 값을 연산에 사용하기 때문이다. 이 처리가 불가능한 것은 아니지만 TS에서는 이를 명시적으로 연산이 가능한 숫자와 같이 처리를 해 줘야 한다.

🔥 How to fix ?

arr.sort(a: IMessageData, b: IMessageData): number => +new Date(a.date) - +new Date(b.date)

위와 같이 단항 연산자인 '+'를 지정하여 사용하면 해결된다! (number로 취급하기 때문)

0개의 댓글