7
Vote

Does not allow subtraction between Dates

description

var millis = new Date() - new Date(1970, 0, 1);

generates the following error:

Operator '-' cannot be applied to types 'Date' and 'Date'

I'm not sure the ES specs allow it but the JS engines I've used support this (may be a consequence of Date having a valueOf method).

comments

bjouhier wrote Oct 7, 2012 at 8:41 PM

From http://ecma-international.org/ecma-262/5.1/#sec-11.6.2 and http://ecma-international.org/ecma-262/5.1/#sec-15.9.5.8 subtraction should work on Dates (and on any object with a valueOf method that returns a number).

rwaldron wrote Oct 7, 2012 at 8:53 PM

Unfortunately, the reason subtraction works on Dates in JavaScript is the exact thing that TypeScript exists to prevent. In short, you can't have your cake and coerce it, too. JavaScript allows math operations on Date objects because the operator itself coerces the LHS and RHS values into types it can work with—in this case numbers.

A work around:

Date.now() - +(new Date(1970, 0, 1));

Which will amusing compile to...

Date.now() - +(new Date(1970, 0, 1));

bjouhier wrote Oct 8, 2012 at 9:01 PM

@rwaldron
Valid point.

This a rather minor annoyance anyway and the + prefix workaround is good enough for me (I had fixed it with .getTime() on both operands, which I found a bit heavy).

Thanks.

jonturner wrote Oct 8, 2012 at 9:06 PM

TypeScript doesn't support these kind of coercions because we don't know generally where all the coercions should be applied.

** Closed by jonturner 10/08/2012 2:06PM

jonturner wrote Oct 10, 2012 at 3:21 PM

Reopening for further comment

staxmanade wrote Aug 31, 2013 at 5:01 AM

For anyone starting to convert existing JavaScript into a TypeSript project this will be one that others might often bump into.

It would make it easier on the conversion if the compiler could support it directly. But if the decision is to not, then I think at minimum a WIKI page of common conversion issues and work-arounds would be ideal to put together (and this one on there).

GeoffArmstrong wrote May 3 at 11:17 PM

I agree, this is fine to leave out. Requiring +date is fine.