NR complains about incorrect javascript code - but its not

I got these lines in a function to check for the presence of a sensor:

var t = new Date(msg.payload.attr.lastseen);
var t0 = new Date();
nmsg.payload.diff = (t0 - t) / 1000;

So .diff is the time difference in seconds. In Javascript you should be able to do some arithmetic operations with Date object. However NR is complaining about a type error in this function node:

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

Actually the function works as expected but can I convince NR that this code is correct?

Hello Haegar,

read this thread that i think is related

You can either provide in-line type overrides to force Monaco to think that the dates are numbers. Or you can force the dates to numbers when you create them. My response in that other thread shows you how.

1 Like

Thanks, that thread was helpful. Simple double brackets did not help but a construction like

var t = Date.parse(msg.payload.lastupdated);
var t0 = Number(new Date());

did the job :wink:
I hope this bug in the Monaco editor is corrected sometime..

Use instead of constructing a date object and it will already be a number (epoch)

Also, use t.valueOf() to get the epoch from your parsed date.

I'm not sure it's a bug. The description is gives is correct.

A parser which reports a syntax error (and not a warning) which is not true is definitely a bug, what else? It leads to a NodeRed complain message everytime you deploy a flow.
But I have seen the discussion on this on the other thread.

That's correct, it isn't a bug. Monaco is correct, it is because JavaScript isn't strongly typed and that can result in incorrect processing of date objects.

The error comes from Node-RED's treatment of Monaco. The warning from the type checker in Monaco comes from the Typescript engine and in typescript misuse of a date object IS an error. It is just that JavaScript natively lets you get away with it. Doesn't make it right. :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.