Monaco editor does not allow subraction of dates

I am not sure where to report this. When using the Monaco editor this code, in a function node, generates an error.

const d1 = new Date()
const d2 = new Date(d1.getTime() + 1000)
msg.payload = d2 - d1
return msg;

Hovering over d2 in the third line shows:

I've noticed such issues occasionally in VScode as well.

If you really want to get rid of it, you can force the type checker:

const d1 = /** @type {number} */ (new Date())
const d2 = /** @type {number} */ (new Date(d1.getTime() + 1000))
msg.payload = d2 - d1
return msg;

Note the brackets round the actual values though. There is an issue in VSCode at least where forcing the type inline doesn't work unless you include the brackets.

Alternatively, you could use Date.parse(d1.getTime() + 1000)) (untested) which should return an integer anyway.

Or Number(new Date()) will also work. Or even (new Date()).getTime() which should also return an integer.

In simple terms, It's something to do with type definitions and what is supported by the subtract operator. Typically objects don't know how to be added/subtracted from one another however some objects (like Date) have a prototype named valueOf that is automatically executed by the V8 engine (under the hood) when you try to run d1+d2

As for whether Monaco should know about this or whether it is a deliberate "good housekeeping" measure - I don't know. I'll look into it some time.

Essentially, you are subtracting numbers so use valueOf...

msg.payload = d2.valueOf() - d1.valueOf()

... Or coerce the type using jsdoc like Julian shows.

@TotallyInformation @Steve-Mcl, yes there are easy workarounds, I was just reporting it in case it is something that should be looked at.

1 Like

I found swapping for solved the error.

Yup, that would also do it! So that is at least 5 ways - gotta wonder about JavaScript sometimes!

And soon to be 6 with Temporal


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