타입스크립트 에러 해결 (단항 더하기 연산자) : The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)
Date나 Math.random을 사용할 때, 타입스크립트 에러가 발생한 경우가 있을 것이다.
나의 경우에는 다음과 같이 Math.random으로 생성한 number에 toFix 메서드를 적용한 값에 *10 연산을 추가하니 에러가 발생하였다.
const rn = Math.random().toFixed(3) * 10;
/*
The left-hand side of an arithmetic operation
must be of type 'any', 'number', 'bigint' or an enum type.
ts(2362)
*/
자바스크립트로는 연산이 가능하지만, 타입스크립트에서는 에러가 발생한다.
타입스크립트 입장에서는 Math.random()의 결과물이 연산이 가능한지 불명확하기에 그런 것 같다.
이런 경우, 다음과 같이 단항 더하기 연산자(Unary plus) +를 붙여줌으로써, 연산 가능하게 만들어 에러를 없앨 수 있다.
const rn = +Math.random().toFixed(3) * 10;
// No Error!
그리고 단항 더하기 연산자가 정확히 어떻게 작용하는지 몇가지 예제를 통해 확인해 보았다.
const t1 = 100;
console.log(+t1); // 100
const t2 = -100;
console.log(+t2); // -100
const t3 = true;
console.log(+t3); // 1
const t4 = '';
console.log(+t4); // 0
const t5 = '123';
console.log(+t5); // 123
const t6 = "Hi";
console.log(+t6); // NaN
위와 같이 자바스크립트에서 숫자로 평가될 수 있는 값들을 명시적으로 숫자로 변환해주는 역할을 해주는 것을 알 수 있다.
마지막의 Hi 문자열과 같이 숫자로 연산될 수 없는 값은 NaN(Not a Number)를 출력하게 된다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus
Unary plus (+) - JavaScript | MDN
The unary plus (+) operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
developer.mozilla.org