Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am getting the following error. I am not able to find out where exactly i went wrong.Can someone help me out with the solution

enter image description here

The code

 function() {
    this.devices.forEach(device => {
      let lastConnect = device.lastConnection.split('+');
      lastConnect = lastConnect[0] + 'Z';
      let diff = Math.abs(new Date() - new Date(lastConnect));//getting error here
}
like image 310
ark Avatar asked Jan 16 '18 04:01

ark


4 Answers

I have found out the issue.

The code you have written works only in Javascript

Math.abs(new Date() - new Date(lastConnect)) .

In order to make it work in Typescript, update the code as shown below:

Math.abs(new Date().getTime() - new Date(lastConnect).getTime());
like image 120
ark Avatar answered Oct 18 '22 19:10

ark


Needless to say, Your code works correctly in Javascript, If you want to get the same result in Typescript, You have 3 options

(1) - With the help of valueOf

let diff = Math.abs(new Date().valueOf() - new Date(lastConnect).valueOf());

(2) - With the help of getTime

let diff = Math.abs(new Date().getTime() - new Date(lastConnect).getTime());
// or
let diff = new Date().getTime() - new Date(lastConnect).getTime();

(3) - With the help of any

let diff = Math.abs(<any>new Date() - <any>new Date(lastConnect))
like image 20
AbolfazlR Avatar answered Oct 18 '22 17:10

AbolfazlR


The simplest answer would be

Math.abs(<any>new Date() - <any>new Date(lastConnect));
like image 16
Sudhanshu sharma Avatar answered Oct 18 '22 18:10

Sudhanshu sharma


No need for Math.abs() to answer this question...

Just using getTime() method converts a Date into a number (Date.prototype.getTime()) so you can make the operation without that error

Check on this example

like image 10
Cruz Jurado Avatar answered Oct 18 '22 17:10

Cruz Jurado